jQuery复选框选中/取消选中

use*_*985 39 checkbox jquery

检查/取消选中位于触发我的函数的元素内的复选框的正确方法是什么?

这是我的代码:

<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');
    }
});
Run Code Online (Sandbox Code Playgroud)

问题是我只能检查并取消选中每个方框一次.在我检查并取消选中后,它仍然会添加/删除类,但从不再次检查一个框(即使我单击复选框,而不是表行).

我尝试过使用.bind('click')触发器,但结果却是一样的.

有解决方案吗

Jai*_*Jai 45

使用.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');
    }
 });
Run Code Online (Sandbox Code Playgroud)

变化:

  1. input:checkbox.
  2. 比较the lengthchecked checkboxes.


Adi*_*dil 20

使用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');
    }
});
Run Code Online (Sandbox Code Playgroud)

对于像checked这样的属性,请使用prop而不是attr

从jQuery 1.6开始,.attr()方法为尚未设置的属性返回undefined.要检索和更改DOM属性(如表单元素的已检查,已选择或已禁用状态),请使用.prop()方法

  • 实际上这是正确的解决方案.接受的答案有一些问题.谢谢你的解决方案. (2认同)

mah*_*moh 5

 $('mainCheckBox').click(function(){
    if($(this).prop('checked')){
        $('Id or Class of checkbox').prop('checked', true);
    }else{
        $('Id or Class of checkbox').prop('checked', false);
    }
});
Run Code Online (Sandbox Code Playgroud)