我将一个事件设置为包装器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>
所以,基本上,如果我点击包装警报会弹出一些消息,但如果我点击按钮会发生其他事情,问题是按钮是来自包装器的子项,所以2个事件会一次触发.
我试着用if(e.target!== this)返回;但只适用于一个孩子,或一些基本结构.
解决方法
您可以使用stopPropagation方法.
Prevents the event from bubbling up the DOM tree,preventing any parent handlers from being notified of the event.
$(".inside-alert").on("click",function(event){ event.stopPropagation() alert('this is my BUTTON' + event.target); // dont pop-up anything });