简体   繁体   English

停止传播到附加元素

[英]stopping propagation to appended elements

Updated: 更新:

I don't understand why this stopPropagation is not preventing bubbling. 我不明白为什么这个stopPropagation不会阻止冒泡。

http://jsfiddle.net/E6NS5/6/ http://jsfiddle.net/E6NS5/6/

$('#content').click(function () {
    alert('prop failed');
});


$('#wrapper').on('click', '.button', function (e) {
    e.stopPropagation();
    alert('test clicked');

});

HTML HTML

<div id="wrapper">
    <div id="content">
        <div id="test" class="button">Top Button</div>
    </div>
</div>

You want the .stopPropagation() call in the event handler for #content , not #wrapper : 您希望在#content的事件处理程序中调用.stopPropagation() ,而不是#wrapper

var test = '<div id = "test" class = "button">Test</div> ';
$('#content').click(function (e) {
    e.stopPropagation();
    alert('prop failed');
});
$('#content').append(test);
$('#wrapper').on('click', '.button', function () {
    alert('test clicked');
});

jsFiddle example jsFiddle例子

The problem is that both events are bind with the "wrapper" class. 问题是两个事件都与“包装器”类绑定。 In this example, the on key word will start with the wrapper class and filter the descendent rather than trigger the event for the .button - thus stopPropagation will not work jsfiddle because they are both at the same level. 在这个例子中,on关键字将以包装类开始并过滤后代而不是触发.button的事件 - 因此stopPropagation将不起作用jsfiddle,因为它们都在同一级别。

$('.button').on('click', function (e) {
alert('test clicked');

e.stopPropagation();
});

More information at jquery api 有关jquery api的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM