This question already has an answer here:
这个问题在这里已有答案:
- Event binding on dynamically created elements? 23 answers
动态创建元素的事件绑定? 23个答案
I'm sure this is something that AJAX gurus learn very early on, but this is the first time I've run into it. Using jQuery, I have assigned .click() handlers to certain CSS classes. However, if I reload some of the content via AJAX, the .click() handlers are not firing for that content.
我确信这是AJAX大师很早就学到的东西,但这是我第一次碰到它。使用jQuery,我已经为某些CSS类分配了.click()处理程序。但是,如果我通过AJAX重新加载某些内容,则.click()处理程序不会针对该内容触发。
It seems I have two choices:
看来我有两个选择:
- put my .click() handler assignments within a JScript function, and call it every time content is refreshed via AJAX.
- use onclick="" rather than jQuery within my AJAX content.
将我的.click()处理程序赋值放在JScript函数中,并在每次通过AJAX刷新内容时调用它。
在我的AJAX内容中使用onclick =“”而不是jQuery。
So far, it seems #1 would be the best; it's more consistent and yields smaller HTML for AJAX.
到目前为止,#1似乎是最好的;它更加一致,并为AJAX产生更小的HTML。
Is there another way to do it? Perhaps a different way of assigning the .click() handlers from the outset?
还有另一种方法吗?也许是从一开始就分配.click()处理程序的另一种方式?
3 个解决方案
#1
4
You are looking for the live()
method instead.
您正在寻找live()方法。
$('selector').live('click', function(){
// your code.......
});
The live
works for elements present now or in the future.
现在或将来出现的元素的现场作品。
#2
3
If you are using jQuery 1.4+, .live() is part of the core. If not then there is a plugin called livequery that provides the functionality you are looking for.
如果您使用的是jQuery 1.4+,则.live()是核心的一部分。如果没有,则会有一个名为livequery的插件,它提供您正在寻找的功能。
#3
1
Check out the bind or live methods, check this out: http://api.jquery.com/live/
查看绑定或实时方法,请查看:http://api.jquery.com/live/
#1
4
You are looking for the live()
method instead.
您正在寻找live()方法。
$('selector').live('click', function(){
// your code.......
});
The live
works for elements present now or in the future.
现在或将来出现的元素的现场作品。
#2
3
If you are using jQuery 1.4+, .live() is part of the core. If not then there is a plugin called livequery that provides the functionality you are looking for.
如果您使用的是jQuery 1.4+,则.live()是核心的一部分。如果没有,则会有一个名为livequery的插件,它提供您正在寻找的功能。
#3
1
Check out the bind or live methods, check this out: http://api.jquery.com/live/
查看绑定或实时方法,请查看:http://api.jquery.com/live/