jq全选和不全选的问题?

如题,想要做一个复选框的选择功能,单击全选的时候checkd=true,再次单击的时候checked= false,但是checkbox的选择勾没有去掉,同时还想加个子选项不选中了,全选按钮去除样式

请问是啥子情况?

阅读 4.5k
7 个回答

取消全选的时候,如果用jQuery写的,用.prop('checked',false),不用.attr('checked',false);

要读取DOM的属性如checked和selected, 使用 prop

有checked这个属性时,就代表了选中,和其值为true或是false无关。

input 上的 checked 属性去掉就行了.

//全选
function CheckedAll(){
$(':checkbox').prop('checked','checked');
}

//全不选
function CheckedNo(){
$(':checkbox').attr('checked','');
}

之前写过全选,有点麻烦,用的是遍历的方法,可以参考下。

    
<table class="table">
  <thead>
    <tr>
      <th class="th-check"><input type="checkbox" id="checkAll"></th>
      <th class="th-title">标题</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="td-check"><input type="checkbox" name="message" /></td>
      <td class="td-title">浅谈</td>
    </tr>
    <tr>
      <td class="td-check"><input type="checkbox" name="message" /></td>
      <td class="td-title">文化</td>
    </tr>
    <tr>
      <td class="td-check"><input type="checkbox" name="message" /></td>
      <td class="td-title">小说</td>
    </tr>
  </tbody>
</table>

  //全选按钮
  //全选和全部选切换开关
  var onOff = true;

  $("#checkAll").click(function(){
    if(onOff){
      $("[name=message]:checkbox").attr("checked",true);
      onOff=false;
    }else{
      $("[name=message]:checkbox").attr("checked",false);
      onOff=true;
    }
  })
//复选框改变触发全选是否选中
  $("[name=message]:checkbox").click(function(){
    var checkA = 0;
    var Len = $("[name=message]:checkbox").length;
    $("[name=message]:checkbox").each(function(){
      if(!this.checked){
        alert(0)
        $("#checkAll").attr("checked",false);
        onOff = true;
      }else{
        alert(0)
        checkA += 1;
      }
    })

    if(checkA==Len){
      $("#checkAll").attr("checked",true);
      onOff = false;
    }
  })

直接上代码

<input type="checkbox" id="checkbox_all" value="" checked="checked">全选
<input type="checkbox" name="checkbox_application" value="1" checked="checked"> 测试1
<input type="checkbox" name="checkbox_application" value="2" checked="checked"> 测试2
<input type="checkbox" name="checkbox_application" value="3" checked="checked"> 测试3
<input type="checkbox" name="checkbox_application" value="4" checked="checked"> 测试4
<input type="checkbox" name="checkbox_application" value="5" checked="checked"> 测试5
<input type="checkbox" name="checkbox_application" value="6" checked="checked"> 测试6

 $(function() {
        $("#checkbox_all").click(function() {
            $('input[name="checkbox_application"]').attr("checked",this.checked);
        });
        var $subBox = $("input[name='checkbox_application']");
        $subBox.click(function(){
            $("#checkbox_all").attr("checked",$subBox.length == $("input[name='checkbox_application']:checked").length ? true : false);
        });
    });
推荐问题