1 回答
TA贡献1864条经验 获得超6个赞
发生这种情况是因为当您勾选复选框时,您的代码将从.button元素中删除点击侦听器,并且在未选中复选框时您不会将其设置回原处。
因此,如果您希望在.button取消选中复选框时再次触发元素上的点击侦听器,您可以执行下面提到的两件事中的任何一件。
首先,您可以在复选框的侦听器中的else块之后添加一个块。以下代码适用于这种方法: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');
});
}
});
但我不会推荐上述方法,因为它会不必要地增加代码的大小。
这是第二种和更好的方法。在点击事件处理函数中,您可以添加一个if语句来检查复选框是否被勾选。下面是相同的代码:
$(".button").on('click', function(){
if (! $("#check").is(':checked')) {
// This will only be fired if checkbox is not checked
$(this).toggleClass('active')
}
});
您可以根据需要将此 if 添加到任何其他块。
使用上述代码的主要优点是:
与第一种方法相比,代码不会增加
您不需要change复选框的侦听器(是的!只需将其删除即可!)
添加回答
举报