本文实例讲述了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代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
< 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代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
<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程序设计有所帮助