阻止执行自定义事件

Prevent custom event from executing

本文关键字:事件 自定义 执行      更新时间:2024-05-09

我想在单击子项时防止在父项上发生自定义事件。请注意,我没有权限访问父事件的代码。我试过在按钮上执行e.preventDefault(),但没有帮助。

当点击其中的某个内容时,是否有任何方法可以忽略所有父事件?

$(function(){
  // Note that this is just an example, I don't have access to this code
  // This is some custom event inside custom plugin
  $('.container').on('click', function() {
    alert('This should be alerted only if you click on green box');
  });
  
  $('.btn').on('click', function() {
    // Here I want to make sure that *parent* events are not triggered.
    alert('Button is triggered, green box should be not triggered');
  });
});
.container {
  width: 300px;
  height: 200px;
  background: green;
  padding-top: 100px;
}
.btn {
  width: 100px;
  height: 100px;
  display: block;
  margin: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <button class="btn">Click Me</button>
</div>

由于您使用的是jQuery,因此可以使用event.stopPropagation()方法。event.stopPropagation()方法停止将事件冒泡到父元素,从而阻止执行任何父事件处理程序。你可以在这里看到它的作用

   $(document).ready(function () {
       $("#button").click(function (event) {
           alert("This is the button.");
           // Comment the following to see the difference
           event.stopPropagation();
       });
       $("#outerdiv").click(function (event) {
           alert("This is the outer div.");
       });
   });

在这个简单的示例中,如果单击按钮,事件将由其自己的处理程序处理,并且不会在DOM层次结构中出现气泡。您可以在按钮上添加一个调用event.stopPropagation()的非常简单的处理程序,它不会弹出。无需干扰父级的JS。