本文實例講述了js實現checkbox全選、不選與反選的方法。分享給大家供大家參考。具體分析如下:
一、思路:
1. 獲取元素
2. 給全選 不選 反選添加點擊事件
3. 用for循環checkbox
4. 把checkbox的checked設置為true即實現全選
5. 把checkbox的checked設置為false即實現不選
6. 通過if判斷,如果checked為true選中狀態的,就把checked設為false不選狀態,如果checked為false不選狀態的,就把checked設為true選中狀態。
二、html代碼:
<input type="button" value="全選" id="sele"/><input type="button" value="不選" id="setinterval"/><input type="button" value="反選" id="clear"/><div id="checkboxs"> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br /> <input type="checkbox"/><br /></div>
三、js代碼:
<script>window.onload=function(){ var sele=document.getElementById('sele');//獲取全選 var unsele=document.getElementById('setinterval');//獲取不選 var clear=document.getElementById('clear');//獲取反選 var checkbox=document.getElementById('checkboxs');//獲取div var checked=checkbox.getElementsByTagName('input');//獲取div下的input//全選 sele.onclick=function(){ for(i=0;i<checked.length;i++){ checked[i].checked=true } }//不選 unsele.onclick=function(){ for(i=0;i<checked.length;i++){ checked[i].checked=false } }//反選 clear.onclick=function(){ for(i=0;i<checked.length;i++){ if(checked[i].checked==true){ checked[i].checked=false } else{ checked[i].checked=true } } }}</script>
希望本文所述對大家的javascript程序設計有所幫助。
新聞熱點
疑難解答