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

Using .on() and e.stopPropagation() on dynamic elements

本文关键字:stopPropagation on 动态 元素      更新时间:2023-09-26

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

$(".container").children().on('click',function(e){
  e.stopPropagation();    
});
$(".container").on("click",function(){
  alert("outside the box?");    
})​

下面是一个jsFiddle设置来演示它的功能。当您点击白色框外的任何位置时,都会发出警报。

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

这里是第二个jsFiddle,您必须首先单击一个链接来创建元素。一旦你做到了这一点,理论上同样的剧本会奏效,但事实并非如此。这种方法缺少什么?

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

$(父级选择器).on(事件,动态子级选择器,处理程序);

所以你重写的代码会简单地是这样的:

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

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

jsFiddle演示

简而言之,您需要将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?");    
})​

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

有关更多详细信息,请查看官方网站"直接和委托事件"部分的".on()"

演示

当使用.on将事件处理程序绑定到元素时,绑定到的目标必须存在于domocument中。

$('body').on('click', '.container > *', function(e){
  e.stopPropagation();    
});
$('body').on("click",'.container',function(){
  alert("outside the box?");    
})​

您需要将.on()绑定到父级。

您要做的是将处理程序绑定到侦听事件的父级,然后检查该事件是否由与该选择器匹配的元素触发。

$("body").on("click", '.container',function(){
  alert("outside the box?");    
})​

此处更新了fiddle

根据jQuery.on():的文档

事件处理程序仅绑定到当前选定的元素;他们必须在代码调用.on()时存在于页面上。

您必须将事件绑定到父容器。也许是这样。