本文实例为大家分享了js实现全选和全不选的具体代码,供大家参考,具体内容如下

非常简洁的几行原生js实现全选和全不选,大神们可以在此基础上加上反选功能。

<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <title>全选、全不选</title>
</head>
<body>
<table border="1">
 <tr>
 <td><input type="checkbox" name="mmAll" onclick="All(this, 'mm[]')"></td>
 </tr>
 <tr><td><input type="checkbox" value="1" name="mm[]" class="check" id="ids1" onclick="Item(this, 'mmAll')"></td></tr>
 <tr><td><input type="checkbox" value="2" name="mm[]" class="check" id="ids2" onclick="Item(this, 'mmAll')"></td></tr>
 <tr><td><input type="checkbox" value="3" name="mm[]" class="check" id="ids3" onclick="Item(this, 'mmAll')"></td></tr>
 <tr><td><input type="checkbox" value="4" name="mm[]" class="check" id="ids4" onclick="Item(this, 'mmAll')"></td></tr>
 <tr><td><input type="checkbox" value="5" name="mm[]" class="check" id="ids5" onclick="Item(this, 'mmAll')"></td></tr>
 <tr><td><input type="checkbox" value="6" name="mm[]" class="check" id="ids6" onclick="Item(this, 'mmAll')"></td></tr>
</table>
</body>
</html>
<script type="text/javascript">
 //Check all
 function All(e, itemName)
 {
  var aa = document.getElementsByName(itemName);
  for (var i=0; i < aa.length; i++)
 
   aa[i].checked = e.checked; //得到那个总控的复选框的选中状态 
 }
 
 //Single select
 function Item(e, allName)
 {
  var all = document.getElementsByName(allName)[0];
  if(!e.checked) all.checked = false;
  else
  {
   var aa =document.getElementsByName(e.name);
   for (var i=0; i<aa.length; i++)
    if(!aa[i].checked) return;
   all.checked= true;
  }
 }
</script>

效果图:

推荐教程:《JS教程》