简体   繁体   English

.stopPropagation()和冒泡-有人可以向我解释吗?

[英].stopPropagation() and bubbling - can someone explain it to me?

I have a stupid question. 我有一个愚蠢的问题。 Can somebody explain me, why event still starts on .outer ? 有人可以解释一下,为什么事件仍然在.outer.outer吗? Even when I have set .stopPropagation() . 即使当我设置了.stopPropagation() I suppose, I don't understand the issue correctly. 我想我不正确理解这个问题。 When I click on .inner , event should not bubble up to .outer 当我单击.inner ,事件不应起泡至.outer

HTML: HTML:

<div class="outer">asdsad
    <div class="inner">asdadsasd</div>
</div>

JavaScript: JavaScript的:

$('.outer').on('click', function(e) {
    e.stopPropagation();
    $('.inner').toggleClass('hidden');
})

Fiddle 小提琴

You need to use: 您需要使用:

$('.inner').on('click', function (e) {   
    e.stopPropagation();
})

$('.outer').on('click', function (e) {   
    $('.inner').toggleClass('hidden');    
})

since e.stopPropagation() prevent event buble up not down the DOM tree 因为e.stopPropagation()防止事件冒泡 ,而不是在DOM树下

Updated Fiddle 更新小提琴

If you want to handle click on .inner different from click on .outer, you should have two event handlers. 如果要处理.inner的单击与.outer的单击不同,则应具有两个事件处理程序。 In the .inner click handler you can then prevent the event from bubbling up, so that clicking on .inner will not trigger the click event handler on .outer 然后,您可以在.inner click处理程序中防止事件冒泡,因此单击.inner不会触发.outer上的click事件处理程序。

$('.inner').on('click', function(e) {
   ...
   e.stopPropagation();
});

$('.outer').on('click', function(e) {
   ...
});

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

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