检查/取消选中放置在触发我的函数的元素内的复选框的正确方法是什么?
这是我的代码:
<table id="news_list">
<tr>
<td><input type="checkbox" name="news[1]" /></td>
<td>TEXT</td>
</tr></table>
$("#news_list tr").click(function() {
var ele = $(this).find('input');
if(ele.is(':checked')){
ele.removeAttr('checked');
$(this).removeClass('admin_checked');
}else{
ele.attr('checked', 'checked');
$(this).addClass('admin_checked');
}
});
问题是我只能选中和取消选中每个框一次。在我选中和取消选中后,有时它仍然会添加/删除类,但不会再次选中某个框(即使当我单击复选框而不是表行时)。
我尝试过使用 .bind('click') 触发器,但结果相同。
有什么解决办法吗?
最佳答案
使用 .prop()
代替,如果我们使用您的代码,则进行如下比较:
看例子jsbin :
$("#news_list tr").click(function () {
var ele = $(this).find(':checkbox');
if ($(':checked').length) {
ele.prop('checked', false);
$(this).removeClass('admin_checked');
} else {
ele.prop('checked', true);
$(this).addClass('admin_checked');
}
});
变化:
- 将
input
更改为:checkbox
。 - 比较
已选中复选框
的长度
。
关于jQuery 复选框选中/取消选中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14769408/