javascript checkbox全选,反选

主要用到dom api的

document.getElementById("id");//获取ID为"id"的DOM对象

document.getElementsByTagName(“input”)//获取Document下所有的Input对象

全选效果

效果:

代码:

<style>
*{ margin:0; padding:0}
#checkList{ line-height: 22px; font: normal 12px/22px simsun; padding:2px 0;}
#checkList th{ text-align:center;}
#checkList td{}
</style>
<table id="checkList" width="163" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <th width="50"><label>
      <input type="checkbox" name="checkbox" id="checkbox" />
    </label></th>
    <td width="113">全选</td>
  </tr>
  <tr>
    <th align="center"><input type="checkbox" name="checkbox2" id="checkbox2" /></th>
    <td>1</td>
  </tr>
  <tr>
    <th align="center"><input type="checkbox" name="checkbox3" id="checkbox3" /></th>
    <td>2</td>
  </tr>
  <tr>
    <th align="center"><input type="checkbox" name="checkbox4" id="checkbox4" /></th>
    <td>3</td>
  </tr>
</table>

<script>
(function(){ var checkBoxWrap=document.getElementById("checkList");//表格 var checkAll=checkBoxWrap.getElementsByTagName("tr")[0];//头行 var checkList=checkBoxWrap.getElementsByTagName("input");//所有INPUT checkAll.onclick=function(){ var thisCheckAll=this.getElementsByTagName("input")[0];
//点选过程的BUG已修正
for(var i=1,len=checkList.length;i<len;i++){ checkList[i].checked=thisCheckAll.checked; } }
})()
</script>

实现上面的效果。

checkBoxWrap.getElementsByTagName("tr")[0]; 可以用DOM中的表格相关的集合来替代 checkBoxWrap.rows[0]

反选效果

效果:

代码:

<style>
*{ margin:0; padding:0}
#checkList{ line-height: 22px; font: normal 12px/22px simsun; padding:2px 0;}
#checkList th{ text-align:center;}
#checkList td{}
</style>
<table id="checkList" width="163" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <th colspan="2"><button id="btnInvert" >反选</button></th>
  </tr>
  <tr>
    <th width="50" align="center"><input type="checkbox" name="checkbox2" id="checkbox2" /></th>
    <td width="113">1</td>
  </tr>
  <tr>
    <th align="center"><input type="checkbox" name="checkbox3" id="checkbox3" /></th>
    <td>2</td>
  </tr>
  <tr>
    <th align="center"><input type="checkbox" name="checkbox4" id="checkbox4" /></th>
    <td>3</td>
  </tr>
</table>

<script>
var checkBoxWrap=document.getElementById("checkList");
var invertAll=document.getElementById("btnInvert");
var checkList=checkBoxWrap.getElementsByTagName("input");
invertAll.onclick=function(){    
    for(var i=0,len=checkList.length;i<len;i++){
        checkList[i].checked=!checkList[i].checked;//取自身反
    }
}

</script>
原文地址:https://www.cnblogs.com/wengxuesong/p/3076137.html