在动态元素上使用.on()和e.stopPropagation() [英] Using .on() and e.stopPropagation() on dynamic elements
问题描述
我一直在尝试使用 stopPropagation()
捕获元素之外的点击事件。
I have been experimenting with capturing click events outside of elements using stopPropagation()
.
$(".container").children().on('click',function(e){
e.stopPropagation();
});
$(".container").on("click",function(){
alert("outside the box?");
})
这是一个jsFiddle设置证明它运作。当您点击白框外的任何地方时,都会触发警报。
Here is a jsFiddle set up to demonstrate it functioning. An alert should fire when you click anywhere outside of the white box.
现在,我尝试将相同的原则应用于动态创建的元素。据我所知,jQuery中的事件赋值的 on()
方法应该允许它在不改变脚本的情况下运行。
Now, I am trying to have the same principle applied to dynamically created elements. As far as I understand, the on()
method of event assignment in jQuery should allow this to function without changing the script.
这是第二个jsFiddle ,您必须先点击链接创建元素。一旦你完成了这个,理论就是相同的脚本可以工作,但事实并非如此。我对这个方法有什么看法?
Here is a second jsFiddle where you must first click a link to create the elements. Once you have done this, the theory is that the same script will work, but it does not. What am I missing about this method?
推荐答案
简而言之,你需要把放在()
在现有父元素上使其有效:
In short word you need to put on()
on existing parent element to make it works:
$('body').on('click', 'a', function(e){
e.preventDefault();
$('<div class="container"><div class="box"></div></div>').appendTo('body');
$(this).remove();
});
$('body').on('click', '.container > *', function(e){
e.stopPropagation();
});
$('body').on('click', '.container', function(){
alert("outside the box?");
})
代码: http://jsfiddle.net/GsLtN/5/
有关详情,请查看'。on()'在官方网站的直接和委派活动部分
For more detail check '.on()' on official site at section 'Direct and delegated events'
这篇关于在动态元素上使用.on()和e.stopPropagation()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!