1

mouseenter在元素上使用或之类的任何事件都不适用于使用、或click加载的元素。infinitescrolljquery.loadjquery.ajax

我不明白为什么。我知道需要调用函数,但是单击事件应该仍然有效,因为加载的元素具有相同的类等,但它们没有!

该事件不仅不起作用,而且如果我在新元素加载后回忆它,已经加载的元素现在已经累积了两个事件,所以如果你做类似的事情$('.class').toggleClass('.anotherclass'),它会添加然后删除类,因为现在有两个事件就它而不仅仅是一个。

为什么会这样?我怎么能有一个不会像那样累积的事件?

希望我说清楚了,谢谢!

4

2 回答 2

1

我过去在动态创建需要绑定到它们的事件侦听器的元素时遇到过这个问题,这就是你需要做的:

$(document).on("event", "#selector", function(){
    //Your code here
});

绑定到文档将允许正确触发所有动态事件。只需将事件更改为您需要的内容以及您需要的选择器,它就会起作用。

于 2013-07-26T15:01:25.753 回答
0

这实际上取决于您如何附加事件处理程序。例子:

// 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);

我的答案主要在评论中,但基本上区别在于事件处理程序是直接的还是委托的。

于 2013-07-26T15:01:15.133 回答