jQuery 复选框选中/取消选中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14769408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery checkbox check/uncheck
提问by user1587985
What would be a proper way to check/uncheck checkbox that's placed inside the element that triggers my function?
检查/取消选中放置在触发我的函数的元素内的复选框的正确方法是什么?
Here's my code:
这是我的代码:
<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');
}
});
The problem is I can check and uncheck each box only once. After I've checked and unchecked sometimes it still does add/remove class, but never checking a box again (even when I click on checkbox, not table row).
问题是我只能选中和取消选中每个框一次。在我选中和取消选中之后,有时它仍然会添加/删除类,但永远不会再次选中一个框(即使我点击了复选框,而不是表格行)。
I've tried using .bind('click') trigger, but it's the same result.
我试过使用 .bind('click') 触发器,但结果相同。
Any solutions?
任何解决方案?
回答by Jai
Use .prop()
instead and if we go with your code then compare like this:
使用.prop()
替代,如果我们与您的代码,然后比较像这样走:
Look at the example jsbin:
查看示例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');
}
});
Changes:
变化:
- Changed
input
to:checkbox
. - Comparing
the length
of thechecked checkboxes
.
- 改
input
到:checkbox
。 - 比较
the length
的checked checkboxes
。
回答by Adil
Use prop() instead of attr() to set the value of checked
. Also use :checkbox
in find method instead of input
and be specific.
使用 prop() 而不是 attr() 来设置 的值checked
。也用于:checkbox
find 方法而不是input
特定的。
$("#news_list tr").click(function() {
var ele = $(this).find('input');
if(ele.is(':checked')){
ele.prop('checked', false);
$(this).removeClass('admin_checked');
}else{
ele.prop('checked', true);
$(this).addClass('admin_checked');
}
});
Use prop instead of attr for properties like checked
使用 prop 而不是 attr 来处理诸如已检查之类的属性
As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method
从 jQuery 1.6 开始,.attr() 方法为尚未设置的属性返回 undefined。要检索和更改 DOM 属性,例如表单元素的选中、选中或禁用状态,请使用 .prop() 方法
回答by mahmoh
$('mainCheckBox').click(function(){
if($(this).prop('checked')){
$('Id or Class of checkbox').prop('checked', true);
}else{
$('Id or Class of checkbox').prop('checked', false);
}
});