1 <!DOCTYPE html>
2 <html lang="en">
3
4 <head>
5 <meta charset="UTF-8">
6 <meta name="viewport" content="width=device-width, initial-scale=1.0">
7 <meta http-equiv="X-UA-Compatible" content="ie=edge">
8 <title>Document</title>
9 </head>
10 <style>
11 table {
12 width: 70%;
13 }
14 </style>
15
16 <body>
17 <table border="1">
18 <tr>
19 <th width='80px'><input type="checkbox" onclick="qunxuan()" name="" id="all">全选</th>
20 <th>姓名</th>
21 <th>性别</th>
22 <th>年龄</th>
23 </tr>
24 <tr>
25 <td><input type="checkbox" name="e" id=""></td>
26 <td>张三</td>
27 <td>男</td>
28 <td>24</td>
29 </tr>
30 <tr>
31 <td><input type="checkbox" name="e" id=""></td>
32 <td>李四</td>
33 <td>女</td>
34 <td>34</td>
35 </tr>
36 <tr>
37 <td><input type="checkbox" name="e" id=""></td>
38 <td>王五</td>
39 <td>男</td>
40 <td>45</td>
41 </tr>
42 </table>
43 <input type="button" value="按钮">
44 </body>
45
46 </html>
47 <script>
48 // 获取需要用的元素对象
49 var allchek = document.querySelectorAll('input[name="e"]');//获取所有在tbody中的复选框
50 var chek = document.querySelector('#all');//获取全选框
51 var fanxuan = document.querySelector('input[type="button"]')//获取反选按钮
52 // 全选事件
53 function qunxuan() {
54 // 遍历所tbody中的复选框
55 for (var i = 0; i < allchek.length; i++) {
56 // 获取全选框的状态
57 var a = chek.checked;
58 // 根据全选框的状态设置tbody中的复选框的状态
59 if (a) {
60 allchek[i].checked = true;
61 } else {
62 allchek[i].checked = false;
63 }
64 }
65 }
66
67 // 遍历tbody中的复选框并注册单击事件
68 for (var i = 0; i < allchek.length; i++) {
69 allchek[i].onclick = function () {
70 // 设置一个参数用来判断是不是tbody中的复选框都选中或不选中
71 var flag = true;
72 // 遍历tbody中的复选框并判断其状态
73 for (var j = 0; j < allchek.length; j++) {
74 var a = allchek[j].checked;
75 // 如果不选中则flag设为false
76 if (!a) {
77 flag = false;
78 break;//只判断第一个,提高效率
79 }
80 }
81 // 通过判断flag的设置全选框的状态
82 if (flag) {
83 chek.checked = true;
84 } else {
85 chek.checked = false;
86 }
87 };
88 }
89
90 // 反选事件
91 fanxuan.onclick = function () {
92 // 遍历所有的tbody中的复选框
93 for (var j = 0; j < allchek.length; j++) {
94 var a = allchek[j].checked;
95 if (a) {
96 allchek[j].checked = false;
97 } else {
98 allchek[j].checked = true;
99 }
100 };
101 // 设置一个参数用来判断是不是tbody中的复选框都选中或不选中
102 var flag = true;
103 // 遍历tbody中的复选框并判断其状态
104 for (var j = 0; j < allchek.length; j++) {
105 var a = allchek[j].checked;
106 // 如果不选中则flag设为false
107 if (!a) {
108 flag = false;
109 break;//只判断第一个,提高效率
110 }
111 }
112 // 通过判断flag的设置全选框的状态
113 if (flag) {
114 chek.checked = true;
115 } else {
116 chek.checked = false;
117 }
118 };
119 </script>