jQuery   发布时间:2022-04-19  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了jquery – 防止在children元素中发生单击大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我将一个事件设置为包装器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更清楚.

所以,基本上,如果我点击包装警报会弹出一些消息,但如果我点击按钮会发生其他事情,问题是按钮是来自包装器的子项,所以2个事件会一次触发.

我试着用if(e.target!== this)返回;但只适用于一个孩子,或一些基本结构.

解决方法

您可以使用stopPropagation方法.

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

大佬总结

以上是大佬教程为你收集整理的jquery – 防止在children元素中发生单击全部内容,希望文章能够帮你解决jquery – 防止在children元素中发生单击所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。