1 回答

TA貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超6個(gè)贊
發(fā)生這種情況是因?yàn)楫?dāng)您勾選復(fù)選框時(shí),您的代碼將從.button元素中刪除點(diǎn)擊偵聽器,并且在未選中復(fù)選框時(shí)您不會(huì)將其設(shè)置回原處。
因此,如果您希望在.button取消選中復(fù)選框時(shí)再次觸發(fā)元素上的點(diǎn)擊偵聽器,您可以執(zhí)行下面提到的兩件事中的任何一件。
首先,您可以在復(fù)選框的偵聽器中的else塊之后添加一個(gè)塊。以下代碼適用于這種方法:ifchange
var check = $("#check");
check.change(function(){
if ($(this).is(':checked')) {
// This will remove the click listener from the button if checkbox is checked
$('.button').off('click');
}
else {
// This will again add the click listener to the button if checkbox is not checked
$(".button").on('click', function(){
$(this).toggleClass('active');
});
}
});
但我不會(huì)推薦上述方法,因?yàn)樗鼤?huì)不必要地增加代碼的大小。
這是第二種和更好的方法。在點(diǎn)擊事件處理函數(shù)中,您可以添加一個(gè)if語句來檢查復(fù)選框是否被勾選。下面是相同的代碼:
$(".button").on('click', function(){
if (! $("#check").is(':checked')) {
// This will only be fired if checkbox is not checked
$(this).toggleClass('active')
}
});
您可以根據(jù)需要將此 if 添加到任何其他塊。
使用上述代碼的主要優(yōu)點(diǎn)是:
與第一種方法相比,代碼不會(huì)增加
您不需要change復(fù)選框的偵聽器(是的!只需將其刪除即可!)
添加回答
舉報(bào)