2012-07-19 34 views
2

我不知道如何可以用jQuery on()jQuery live()已棄用:使用on for mouseenter和mouseout?

$('.box').live({ 
     mouseenter: 
     function() { 
      $(this).children('.menu').stop(true, true).fadeIn(fadeIn); 
     }, 
     mouseleave: 
     function() { 
      $(this).children('.menu').stop(true, true).fadeOut(fadeOut); 
     } 
    }); 

任何想法改寫下面聽衆?

+1

請參閱http://stackoverflow.com/questions/8021436/jquery-1-7-turning-live-into-on和文檔http://api.jquery.com/live/,http:// api .jquery.com /上/。你會發現如何將'.live'轉換爲'.on'的信息。 – 2012-07-19 11:11:09

回答

4
$(document).on('hover', '.box', function(e) { 
    if(e.type == 'mouseenter') { 
    $(this).children('.menu').stop(true, true).fadeIn(fadeIn); 
    } else { 
    $(this).children('.menu').stop(true, true).fadeOut(fadeOut); 
    } 
}); 

相反的document這將是更好地使用這不是動態的.box任何父元素。

閱讀關於.on()

.on()爲代表的事件(又名現場活動)語法是:

$(StaticParent).on(eventName, target, handlerFunction); 
+0

'StaticParent' - 好! – andlrc 2012-07-19 11:11:37

2

對於確切.on相當於:

$(document).on({ 
    mouseenter: function() { 
     $(this).children('.menu').stop(true, true).fadeIn(fadeIn); 
    }, 
    mouseleave: function() { 
     $(this).children('.menu').stop(true, true).fadeOut(fadeOut); 
    } 
}, '.box'); 

雖然這裏的主要好處是,你不需要要使用document,您可以使用在頁面生命週期中保證存在的最接近的父代。