简体   繁体   English

防止事件触发复选框更改

[英]Prevent event firing for checkbox change

I have two event handlers for one single checkbox. 我为一个复选框有两个事件处理程序。 I want to first handler to prevent the second one from firing. 我想要第一个处理程序来防止第二个处理程序触发。 Here is an example: 这是一个例子:

$("#address_cb").change(function(event) {
    alert('foo');
    event.preventDefault();
    event.stopPropagation();
    return false;
});

$("#address_cb").change(function(event) {
    alert('should never display');
});

$("#address_cb").trigger("change");


https://jsfiddle.net/zxzzLkky/5/

How can I achieve it? 我该如何实现?

You need to use Even.stopImmediatePropagation() 您需要使用Even.stopImmediatePropagation()

$("#address_cb").change(function(event) {
   alert('foo');
   event.preventDefault();
   event.stopImmediatePropagation(); //Works
   return false; //would call event.preventDefault() and event.stopPropagation() but not stopImmediatePropagation()
});

as both of your events fire on the same event level. 因为您的两个事件都在同一事件级别上触发。 As an alternative you might just return false for your callback as jQuery will care about the rest. 作为替代方案,您可能只为回调返回false,因为jQuery会关心其余部分。

See event.preventDefault() vs. return false for differences on return false method 请参阅event.preventDefault()与return false,以了解return false方法的区别

Try using event.stopImmediatePropagation() instead of event.stopPropagation();. 尝试使用event.stopImmediatePropagation()而不是event.stopPropagation();。 Please test it propely. 请正确测试。 Hope this work. 希望这项工作。 Reference https://api.jquery.com/event.stopimmediatepropagation/ 参考https://api.jquery.com/event.stopimmediatepropagation/

$("#address_cb").change(function(event) {
    alert('foo');
    event.preventDefault();
    event.stopImmediatePropagation();
    return false;
}); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM