使用jQuery按钮取消选中复选框。
使用jQuery按钮取消选中复选框。
这个问题已经有答案了:
这个任务似乎很简单,但我的代码不起作用。
我有一个带有一些行的表格,每一行都有一个复选框,在下面我放了一个\"删除全部\"按钮来取消勾选框。
这是我的代码:
$('#remove-button').click(function(){ $('input:checked').prop('checked',false); //e.stopPropagation(); // I tried also with this // $('input:checked').removeAttr('checked'); // or this syntax });
当我点击按钮时,所有输入框都被取消勾选,但这不是由于我的代码,因为当我注释掉这段代码时,当我点击按钮时也会发生这种情况。我还发现,当我点击并取消输入框时,我的网站似乎会刷新,因为页面会滚动到顶部。
我还添加了另一个按钮来选中输入框:
$('#add-button').click(function(e){ $('input').prop('checked',true); //e.stopPropagation(); // I tried also with this // $('input:checked').removeAttr('checked'); // or this syntax });
当我触发它时,输入框被选中,一秒钟后我的网站刷新并且一切都消失了。
我使用最新的Firefox和Chrome,并使用jQuery - 1.11(但也检查了1.8.0和1.7.1)。
还附加了
有人知道错在哪里吗?
admin 更改状态以发布 2023年5月21日
“checked”属性是布尔类型,但当它不存在时,它的值为假。
如果您不想在点击时提交或不跳转到链接,则可以使用e.preventDefault()
方法。
因此,您需要这样做:
$('#remove-button').click(function(e) { $('input:checked').removeAttr('checked'); e.preventDefault(); }); $('#add-button').click(function(e) { var input = $('input.input-to-check') input.attr('checked', 'checked'); e.preventDefault(); });