[英]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.