【问题标题】:event not working on loaded elements事件不适用于加载的元素
【发布时间】:2013-07-26 14:56:34
【问题描述】:
在元素上使用任何事件(例如 mouseenter 或 click)将不适用于以 infinitescroll、jquery.load 或 jquery.ajax 加载的元素。
我不明白为什么。我知道需要调用函数,但是单击事件应该仍然有效,因为加载的元素具有相同的类等,但它们没有!
该事件不仅不起作用,而且如果我在新元素加载后回忆它,已经加载的元素现在已经累积了两个事件,因此如果你执行$('.class').toggleClass('.anotherclass') 之类的操作,它将添加然后删除该类因为现在有两个事件,而不仅仅是一个。
为什么会这样?我怎么能有一个不会像那样累积的事件?
希望我说清楚了,谢谢!
【问题讨论】:
标签:
jquery
events
infinite-scroll
jquery-load
【解决方案1】:
我过去在动态创建需要绑定事件侦听器的元素时遇到过这个问题,这就是你需要做的:
$(document).on("event", "#selector", function(){
//Your code here
});
绑定到文档将允许正确触发所有动态事件。只需将事件更改为您需要的内容以及您需要的选择器,它就会起作用。
【解决方案2】:
这实际上取决于您如何附加事件处理程序。示例:
// This will be attached to all currently existing elements with class
// .class, but not to future ones
$('.class').click(handler);
使用on():
// This is attached to the document and if the target of the event
// matches the provided selector then the event would be triggered
// on it. Here it doesn't matter whether the element with class
// .class existed at the time the handler was attached
$(document).on('click', '.class', handler);
我的答案主要在 cmets 内部,但基本上区别在于事件处理程序是直接的还是委托的。