jQuery 如何将 .hover() 绑定到动态创建的“li”元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14950321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:08:41  来源:igfitidea点击:

How to bind .hover() to dynamically created "li" elemtent?

jquery

提问by Tadas V.

All the solutions I was able to find suggests to use .live()method. But as of today it is deprecated.

我能找到的所有解决方案都建议使用.live()方法。但从今天起,它已被弃用。

.hover()works perfectly on "li" elements not created dynamically. But once I append new "li" .hover()is not triggered at all.

.hover()完美适用于非动态创建的“li”元素。但是一旦我追加新的“li”.hover()就根本不会被触发。

Anybody has figured this one out?

有没有人想过这个?

回答by jfriend00

The "hover" event has been deprecated with delegated event handling such as .on()per the .on()jQuery doc pages.

“悬停”事件已被委派事件处理弃用,例如.on()每个.on()jQuery 文档页面

Instead, you need to use .on()delegated event handling with mouseenter and mouseleave and an event handler for each.

相反,您需要使用.on()带有 mouseenter 和 mouseleave 的委托事件处理以及每个的事件处理程序。

For example:

例如:

$(document).on("mouseenter", "li", function() {
    // hover starts code here
});

$(document).on("mouseleave", "li", function() {
    // hover ends code here
});

In your real code, you would select a static parent object that is much closer to the dynamic litags than the documentobject for better performance.

在您的实际代码中,您将选择一个lidocument对象更接近动态标签的静态父对象,以获得更好的性能。

回答by Iswanto San

Use JQuery OnTry this :

使用JQuery试试这个:

$(document).on('hover', 'li', function () {

});

回答by Meherzad

Try this

尝试这个

Edit: Sry missed the deprecated event

编辑:Sry 错过了已弃用的事件

$(document).on("mouseenter", "li", function(){
       //Your code
});

http://api.jquery.com/live/

http://api.jquery.com/live/

fiddle

小提琴