【问题标题】:jQuery live() deprecated: Using on for mouseenter and mouseout?jQuery live() 已弃用:将 on 用于 mouseenter 和 mouseout?
【发布时间】:2012-07-19 11:05:59
【问题描述】:

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

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

有什么想法吗?

【问题讨论】:

标签: javascript events deprecated jquery


【解决方案1】:
$(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 );

【讨论】:

    【解决方案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,但您可以只使用保证在页面生命周期内存在的最接近的父级。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-23
      • 2021-10-17
      • 1970-01-01
      • 2015-06-25
      • 2017-04-17
      • 1970-01-01
      • 2012-03-04
      • 1970-01-01
      相关资源
      最近更新 更多