如何绑定.hover()来动态创建"li"元素?

Tad*_* V. 22 jquery

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

.hover()完美地适用于动态创建的"li"元素.但是,一旦我追加新的"李" .hover()根本没有触发.

有谁想过这个吗?

jfr*_*d00 53

"hover"事件已被委托事件处理(例如,.on()根据.on()jQuery doc页面)弃用.

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

例如:

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

$(document).on("mouseleave", "li", function() {
    // hover ends code here
});
Run Code Online (Sandbox Code Playgroud)

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