使用on jQuery 函数。
$(document).on("event", "selectorOfDynamicElements", function() {
// do something
});
JSFIDDLE
在documentation 我们发现这个:
.on( 事件 [, 选择器] [, 数据], 处理程序(eventObject) )
因此,在示例中,我们将使用以下参数检测对document 的点击:
-
events:“点击”
-
selector: ".myFavoriteClass"
直接和委托事件
When a selector is provided, the event handler is referred to as delegated.当事件直接发生在绑定元素上时,不会调用处理程序,而只会调用与选择器匹配的后代(内部元素)。
事件处理程序仅绑定到当前选定的元素;当您的代码调用 .on() 时,它们必须存在于页面上。为确保元素存在并且可以被选择,请在页面 HTML 标记中的元素的文档就绪处理程序内执行事件绑定。
[阅读更多documentation page]
this fiddle 中的问题是您创建了对每个 mouseover 的绑定。
$(document).on('mouseover', '.test', function () {
// the mouseover is detected, "Hey, create a new handler!"
$('.test').bind('mousewheel DOMMouseScroll', function(e) {
// "Ok, sir. Here your code goes"
});
});
您应该简单地拥有以下代码,而不是上面的代码:
$(document).on('mouseover mousewheel DOMMouseScroll', '.test', function (e) {
// here your code goes
});
Updated FIDDLE