繁体   English   中英

防止事件触发复选框更改

[英]Prevent event firing for checkbox change

我为一个复选框有两个事件处理程序。 我想要第一个处理程序来防止第二个处理程序触发。 这是一个例子:

$("#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/

我该如何实现?

您需要使用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()
});

因为您的两个事件都在同一事件级别上触发。 作为替代方案,您可能只为回调返回false,因为jQuery会关心其余部分。

请参阅event.preventDefault()与return false,以了解return false方法的区别

尝试使用event.stopImmediatePropagation()而不是event.stopPropagation();。 请正确测试。 希望这项工作。 参考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