簡體   English   中英

jQuery live()已棄用:使用on進行mouseenter和mouseout嗎?

[英]jQuery live() deprecated: Using on for mouseenter and mouseout?

我想知道如何使用jQuery on()重寫以下偵聽器

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

有任何想法嗎?

$(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);
  }
});

最好使用非動態的.box父元素來代替document

了解有關.on()

代表事件(又稱現場事件)的.on()語法為:

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

對於精確的 .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 ,但是您可以使用保證在頁面生命周期內存在的最接近的父級。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM