如何在尚不存在的元素上注册事件? [英] How to register event on elements that don't yet exist?
问题描述
我正在尝试在这样的元素上注册事件:
I am trying to register a event on elements like this:
$(document).ready(function() {
$('.classname').change(function(){
alert ('This line is never triggered');
});
});
但是问题是.classname元素后来被ajax加载到dom中.那么,在这种情况下如何正确注册事件?只能执行一次(我的意思是,不是每次出现新元素都可以吗?)
But the problem is that .classname elements are later loaded into the dom by ajax. So, how do I correctly register an event in this case? Is it possible to do it only once (I mean, not every time the new element appears?)
推荐答案
提示您使用live()
的答案之外,还可以使用delegate()
,例如:
Further to the answers suggesting that you use live()
, it's also possible to use delegate()
, for example:
$('form').delegate('.classname', 'change', function(){
alert("This will alert when the newly-added element registers a 'change' event.");
});
对于delegate
要分配选择器的元素(.classname')
要,在这种情况下,$('form')
在分配时必须存在于DOM中.
For delegate
the element to assign the selector (.classname')
to, in this case the $('form')
must exist in the DOM at the time of assignment.
已编辑,请注意以下部分(紧随下一个已编辑",直到参考"为止)是"错误":
Edited to note that the following section (following the next 'edited' until the 'Reference') is wrong:
在delegate()
选择器选择的元素和事件为delegate()
-d 确实 的目标之间的元素上调用stopPropagation()
(尽管我以前没有意识到这一点)阻止了授权的发生.
Calling stopPropagation()
on an element between the element selected by the delegate()
selector and the target to which the event is delegate()
-d does somewhat predictably (though I hadn't realised this before) prevent the delegation from occurring.
已编辑,以回答OP中的问题,评论:
Edited in response to question, in comments, from OP:
嘿,刚注意到,如果任何父级的事件处理程序调用stopPropagation,则实时事件将停止!这是正确的吗?
不符合 jQueryAPI (该条目链接到下面):
Not according to the jQueryAPI (the entry is linked-to below):
...由.delegate()
处理的事件将始终传播到委派它们的元素...
...events handled by.delegate()
will always propagate to the element to which they are delegated...
我还没有尝试/验证它,但是即使位于目标元素( $('.classname')
)和delegate()
-d元素($('form')
)之间的元素似乎也要调用/验证stopPropagation()
对delegate()
不应有不利影响.
I've not tried/verified this as yet, but it seems that even if an element that sits between the target element ($('.classname')
) and the delegate()
-d element ($('form')
) calls stopPropagation()
it shouldn't have an adverse effect on the delegate()
.
参考:
这篇关于如何在尚不存在的元素上注册事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!