防止子元素的点击事件发生

4

我将事件设置为一个“包装器div”,但在这个“div”内部,我有一些“按钮”,如何阻止这个“包装器”事件在“按钮”中发生?

html

<div class="wrapper-alert"> <!-- click here will pop-up -->
   <div class="somethingElse"> <!-- click here will pop-up -->
      Some text            
   </div>
   <div class="this-is-my-action">
      <button class="inside-alert">Inside</button> <!-- click here will NOT pop-up-->
   </div>
   <div class="somethingElseTo"> <!-- click here will pop-up -->
      Some text            
   </div>
</div>

我做了一个jsfiddle,以便更清晰地说明。
基本上,如果我点击wrapper-alert,会弹出一些信息,但是如果我点击button,则会发生其他事情,问题在于按钮是容器的子元素,因此两个事件将同时触发。 我尝试使用if (e.target !== this) return;来解决问题,但只适用于一个children或一些基本结构。
1个回答

8
你可以使用 stopPropagation 方法。

阻止事件冒泡到 DOM 树,防止任何父级处理程序收到该事件的通知。

$(".inside-alert").on("click", function(event){
     event.stopPropagation()
     alert('this is my BUTTON' + event.target); // dont pop-up anything
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接