效果图:
1.点击全选:
2.再次点击:
3.源代码
<!DOCTYPE html>
<!--suppress ALL -->
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table>
<tr>
<td>
<label>全选:</label>
<input id="qx" type="checkbox"/>
</td>
</tr>
<tr>
<td>
<label>menu1:</label>
<input id="qx0" type="checkbox"/>
</td>
</tr>
<tr>
<td>
<label>menu2:</label>
<input id="qx1" type="checkbox"/>
</td>
</tr>
<tr>
<td>
<label>menu3:</label>
<input id="qx2" type="checkbox"/>
</td>
</tr>
<tr>
<td>
<label>menu4:</label>
<input id="qx3" type="checkbox"/>
</td>
</tr>
</table>
<script>
//获取全选按钮
var allCheck = document.getElementById("qx");
//给全选按钮增加点击事件
allCheck.addEventListener("click",clickHandler);
for (var i = 0; i <4 ; i++) {
var check = document.getElementById("qx"+i);
check.addEventListener("click",clickHandler);
}
function clickHandler(e) {
//判断是否为全选按钮
if (this === allCheck){
//遍历其他子按钮
for (var i = 0; i <4 ; i++) {
var check = document.getElementById("qx"+i);
//让其他子按钮的状态与全选按钮状态相同
check.checked = allCheck.checked;
}
return;
}
var bool = true;
for (var i = 0; i < 4; i++) {
var check = document.getElementById("qx"+i);
//存在其他子按钮没有被选中时,将bool设置为flse
if (!check.checked){
bool = false;
}
}
//只要存在子按钮没有被选中,全选的选中状态也为false.
allCheck.checked = bool;
}
</script>
</body>
</html>