防止执行自定义事件

时间:2015-02-25 16:47:37

标签: javascript jquery

我希望在点击子项时阻止父项的自定义事件。请注意,我无权访问父事件的代码。我已尝试在按钮上执行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>

1 个答案:

答案 0 :(得分:0)

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

中看到它
   $(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。

相关问题