简体   繁体   English

防止事件冒泡在jQuery中不起作用

[英]prevent event bubling doesn't work in jquery

I have the DOM like this 我有这样的DOM

<div class="modal">
<li>

<div id="block1"></div>
<div id="block2">

<div class="btn-wrap">
<button>cancel</button>
<button>save</button>
</div>

</div>

</li>

I have a click event attached to li and when I click button of block2, that event occurred. 我有一个附在li上的click事件,当我单击block2的按钮时,发生了该事件。 How to prevent that to happened? 如何防止这种情况发生?

I tried using on() but it doesn't work. 我尝试使用on(),但不起作用。

$('.btn-wrap').on('click','button:first-child',function(e){
            e.preventDefault();
            alert('test');
        });

You should use stopPropagation to prevent event bubbling: 您应该使用stopPropagation来防止事件冒泡:

$('.btn-wrap').on('click','button:first-child',function(e){
   e.stopPropagation();
   alert('test');
});

Add event.stopPropagation() to your handler event.stopPropagation() 添加到您的处理程序中

$('.btn-wrap').on('click', 'button:first-child', function(e)
{
    e.preventDefault();
    e.stopPropagation();

    alert('test');
});

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

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