jq實現多選框及反選

1 效果圖css

 

 

2 htmlhtml

<div class="main">
<table>
<tr>
<th><input type="checkbox" id="checkAll" name="checkAll"/><label>全選</label><label>
<a href="#" id="checkNo">反選</a>
</label></th>
</tr>
<tr>
  <td><input type="checkbox" name="item" /><label>選項1</label></td>
</tr>
<tr>
  <td><input type="checkbox" name="item" /><label>選項2</label></td>
</tr>
<tr>
  <td><input type="checkbox" name="item" /><label>選項3</label></td>
</tr>
<tr>
  <td><input type="checkbox" name="item" /><label>選項4</label></td>
</tr>
<tr>
  <td><input type="checkbox" name="item" /><label>選項5</label></td>
</tr><tr>
  <td><input type="checkbox" name="item" /><label>選項6</label></td>
</tr>
</table>
</div>

3 csside

.main{
  height:200px;
  background-color:#CDCDC1;
  font-size:15px;
  font-family:"微軟雅黑";
}

4 jq函數

$(document).ready(function(){
    //判斷子元素是否全選
    var length = $("input[name='item']").length;
    function isCheckAll(){
    var count = 0;
    for(let i =0;i<length;i++){
    if($("input[name='item']").eq(i).prop('checked')){
    count++;
    }
    }
    if(count == length){$("input[name='checkAll']").eq(0).prop('checked',true);}else{
    $("input[name='checkAll']").eq(0).prop('checked',false);
    }
    }
    //全選
   $("input[name='checkAll']").click(function(){
   var _this_ = $(this);
   $("input[name='item']").prop('checked',_this_.prop('checked'));
   })
   //反選
  $("#checkNo").click(function(){
      $("input[name='item']").each(function(){
          $(this).prop('checked',!$(this).prop('checked'));
      });
      isCheckAll();
  })
  //爲每個選項綁定一個判斷全選le
  for(let i=0;i<length;i++){
  $("input[name='item']").eq(i).click(function(){
  isCheckAll();
  })
  }
});

 5 總結this

.prop(); //能夠用來獲取屬性值,也能夠用來設置屬性值,與.attr()相似spa

.each();//爲選中的對象集合的元素遍歷一遍處理函數3d

.length;//獲取選中對象的個數code

6 補充 js實現  2019/10/16,思路不變,只是用原生的js實現htm

window.onload = function(){
  var oCheckAll = document.getElementsByName('checkAll');
  var oCheckNo = document.getElementById('checkNo');
  var oItem = document.getElementsByName('item');
  var length = oItem.length;
  console.log(length);
  console.log(oItem);
  function isCheckedAll(){
    let count = 0;
    for(let i =0;i<length;i++){
      if(oItem[i].checked == true){
        count++;
      }
    }
    if(count == length){
      oCheckAll[0].checked = true ;
    }else{
      oCheckAll[0].checked = false ;
    }
  }
  oCheckAll[0].onclick = function(){
    console.log(1);
    for(let i=0;i<length;i++){
      oItem[i].checked = true;
    }
  }
  oCheckNo.onclick = function(){
    console.log(2);
    for(let i=0;i<length;i++){
      var flag = oItem[i].checked;
      oItem[i].checked = !flag;
    }
    isCheckedAll()
  }
  for(let i =0;i<length;i++){
    oItem[i].onclick = function(){
      isCheckedAll();
    }
  }

}
View Code
相關文章
相關標籤/搜索