在动态元素上使用.on()和e.stopPropagation()

Mil*_*uzz 7 javascript jquery javascript-events

我一直在尝试使用元素捕获元素之外的点击事件stopPropagation().

$(".container").children().on('click',function(e){
  e.stopPropagation();    
});
$(".container").on("click",function(){
  alert("outside the box?");    
})?
Run Code Online (Sandbox Code Playgroud)

这是一个jsFiddle设置来演示它的功能.单击白框外的任何位置时,都会触发警报.

现在,我试图将相同的原理应用于动态创建的元素.据我所知,on()jQuery中的事件赋值方法应该允许它在不更改脚本的情况下运行.

这是第二个jsFiddle,您必须首先单击链接以创建元素.一旦你完成了这个,理论就是相同的脚本可以工作,但事实并非如此.我对这种方法缺少什么?

kap*_*apa 6

当动态添加项目时,您应该将处理程序附加到肯定会在那里的最近的父项 - 在您的情况下,这是body.你可以用on()这种方式来实现的功能delegate()用来提供:

$(selector-for-parent).on(events,selector-for-dynamic-children,handler);

所以你重写的代码就是这样的:

$("body").on('click', '.container', function(e){
    var $target = $(e.target);
    if ($target.hasClass('container')) {
        alert("outside the box!");
    }
});
Run Code Online (Sandbox Code Playgroud)

我曾经e.target找到实际触发事件的元素.在这种情况下,我通过检查项目是否具有container该类来识别该项目.

jsFiddle演示


Sam*_*ich 5

简而言之,您需要放置on()现有的父元素才能使其工作:

$('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?");    
})?
Run Code Online (Sandbox Code Playgroud)

代码:http://jsfiddle.net/GsLtN/5/

有关详细信息,请在官方网站的"直接和委派活动"部分查看".on() "