复选框全选、取消全选、反选 【js读书笔记】

复选框全选、取消全选、反选

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8">
 5         <title>复选框全选、取消全选、反选</title>
 6     </head>
 7     <body>
 8         <h2>checkbox复选框全选、取消全选、反选</h2>
 9         <p>
10             <input type="button" id="allSelect" value="全选"/>
11             <input type="button" id="canelallSelect" value="取消全选"/>
12             <input type="button" id="_select" value="反选" />
13         </p>
14         <input type="checkbox" name="actionSelects" />1<br />
15         <input type="checkbox" name="actionSelects" />2<br />
16         <input type="checkbox" name="actionSelects" />3<br />
17         <input type="checkbox" name="actionSelects" />4<br />
18         <input type="checkbox" name="actionSelects" />5<br />
19     </body>
20     <script type="text/javascript">
21         window.onload=function(){
22             var targets=document.getElementsByName("actionSelects");//获取checkbox 元素
23             var targetsLen=targets.length;//获取checkbox元素的个数
24             
25             document.getElementById("allSelect").onclick=function(){//全选
26                 for(var i=0;i<targetsLen;i++){
27                     targets[i].checked=true;
28                 }
29             };
30             
31             document.getElementById("canelallSelect").onclick=function(){//取消全选
32                 for(var i=0;i<targetsLen;i++){
33                     targets[i].checked=false;
34                 }
35             };
36             document.getElementById("_select").onclick=function(){//反选
37                 for(var i=0;i<targetsLen;i++){
38                     targets[i].checked=!targets[i].checked;//选中取反
39                 }
40             };
41         };    
42     </script>
43 </html>

 

posted @ 2016-04-28 14:34  HollyLearningNotes  阅读(203)  评论(0编辑  收藏  举报