I have 3 buttons, and all of them have event handlers on click.
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".
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.
$('.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:
$(".class2 .button").on("click",function(e){
alert('button')
e.stopPropagation()
})
and it shoud fire first.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.