2

我想知道如何用 jQuery 重写以下监听器on()

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

有任何想法吗?

4

2 回答 2

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 );
于 2012-07-19T11:07:24.190 回答
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,但您可以只使用保证在页面生命周期内存在的最接近的父级。

于 2012-07-19T11:12:38.190 回答