[英]jquery unbind or off click event handler within specific parent
I have 3 buttons, and all of them have event handlers on click. 我有3个按钮,所有按钮都有单击事件处理程序。
If a button is within a specific parent, then there should be no click event on the button. 如果按钮在特定的父项中,则该按钮上不应有任何点击事件。 But rather, a click event should exist at that specifc parent level itself. 但是,应该在该特定父级本身存在单击事件。
In the code below, on clicking the button within .case2
, I was expecting the alert to show "case2 parent clicked", but it still shows the alert "button clicked". 在下面的代码中,单击.case2
的按钮时,我期望警报显示“ case2 parent clicked”,但仍显示警报“ button clicked”。
Why is that happening ? 为什么会这样呢? And how do I correct it ? 我该如何纠正呢?
Thanks. 谢谢。
$('.button').on('click', function (e) { alert('button clicked'); e.stopPropagation(); }); $('.case2') .off('click', '.button', function (e) { e.stopPropagation(); }) .on('click', function (e) { alert('case2 parent clicked'); e.stopPropagation(); });
.case1, .case2, .case3 { margin:1em; padding: 1em; background-color: #0b97c4; width: 5em; height:2em; } .button { padding: 1em; background-color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="case1"> <div class="button"></div> </div> <div class="case2"> <div class="button"></div> </div> <div class="case3"> <div class="button"></div> </div>
Use :not
in the selector. 在选择器中使用:not
。
$('.button:not(.case2 .button)').on('click', function (e) { alert('button clicked'); e.stopPropagation(); }); $('.case2').on('click', function (e) { alert('case2 parent clicked'); e.stopPropagation(); });
.case1, .case2, .case3 { margin:1em; padding: 1em; background-color: #0b97c4; width: 5em; height:2em; } .button { padding: 1em; background-color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="case1"> <div class="button"></div> </div> <div class="case2"> <div class="button"></div> </div> <div class="case3"> <div class="button"></div> </div>
Just for an alternate example, simply only attach the handler and not turn it off. 仅作为另一个示例,仅附加处理程序而不关闭它即可。
var buttons = $('.button');
buttons.not('.case2 .button').on('click', function(e) {
alert('case first');
e.stopPropagation();
});
buttons.parents('.case2').on('click', function(e) {
alert('case2 parent clicked');
e.stopPropagation();
});
Add the ".button" class to your selector: 将“ .button”类添加到选择器中:
$(".class2 .button").on("click",function(e){
alert('button')
e.stopPropagation()
})
and it shoud fire first. 它应该首先火。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.