【问题标题】:standard function works fine but if delegated - does not [duplicate]标准功能工作正常,但如果委托 - 不[重复]
【发布时间】:2020-04-28 15:05:05
【问题描述】:

这很好用:

$('.rollwrap').hover(function() {
    $(this).find('.imgrollb').animate({'bottom' : 0});
    }, function() {
    $(this).find('.imgrollb').animate({'bottom' : '100%'});
    }
);

如果rollwrap 及其内容是动态添加的,我需要委托该功能,但这不起作用:

$(document).on('hover', '.rollwrap', function(){
    $(this).find('.imgrollb').animate({'bottom': 0});
    }, function(){
    $(this).find('.imgrollb').animate({'bottom': '100%'});
    }
);

如何获得与动态内容相同的功能?

【问题讨论】:

  • hover 不是一个事件,它是两个相关事件的快捷方式。 .on() 不允许你提供多个处理函数。
  • @Barmar 我明白了,谢谢,但有什么合乎逻辑的理由为什么允许在静态内容而不是动态内容上使用快捷方式?
  • 静态不允许。 $(".rollwrap").on("hover", function() { ...}, function() {...}) 也不起作用。

标签: javascript jquery


【解决方案1】:

传递给.hover 的两个函数是 mouseenter 和 mouseleave 处理程序,因此您可以使用这些事件进行委托:

$(document).on('mouseenter', '.rollwrap', function(){
  $(this).find('.imgrollb').animate({'bottom': 0});
});
$(document).on('mouseleave', '.rollwrap', function(){
  $(this).find('.imgrollb').animate({'bottom': '100%'});
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-18
    相关资源
    最近更新 更多