checkbox选中状态主要是靠checked属性控制,js获取设置属性可以直接通过.来控制,或者通过getAttribute(),setAttribute()控制
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
table{
border: 1px solid #000000;
border-collapse: collapse;
margin: 0 auto;
}
table td{
border: 1px solid #000000;
}
</style>
<script type="text/javascript">
/**
* 窗口加载完毕之后,注意方法中访问form表单元素的方法
*/
window.onload = function (ev) {
var cbControl = document.forms["my_form"]["cb_control"];
console.log(cbControl.checked);//直接通过.访问属性
//通过getAttribute()方法访问属性,如果没有在html中设置属性的话,返回的是null
console.log(cbControl.getAttribute("checked"));
var cbSubControls = document.forms["my_form"]["cb_sub_control"];
for(var i = 0; i < cbSubControls.length; i++){
console.log(cbSubControls[i].checked);
}
/**
* 给总开关设置点击事件,选中总开关,分开关均要被选中
*/
cbControl.onclick = function () {
var cbStatus = cbControl.checked;
if(cbStatus){
for(var i = 0; i < cbSubControls.length; i++){
cbSubControls[i].checked = true;
}
}else{
for(i = 0; i < cbSubControls.length; i++){
cbSubControls[i].checked = false;
}
}
};
//重置
cbControl.setAttribute("checkedCount", 0);//通过setAttribute()设置属性
cbControl.checkedCount = 0;//直接通过.来设置属性
console.log(cbControl.checkedCount);
console.log(cbControl.getAttribute("checkedCount"));
for(i = 0; i < cbSubControls.length; i++){
cbSubControls[i].checked = false;
}
//给所有分开关设置点击事件
for(i = 0; i < cbSubControls.length; i++){
cbSubControls[i].onclick = function () {
var tmp = 0;
var status = this.checked;
if(status){
tmp = parseInt(cbControl.getAttribute("checkedCount"), 10);
tmp++;
cbControl.setAttribute("checkedCount", tmp);
}else{
tmp = parseInt(cbControl.getAttribute("checkedCount"), 10);
tmp--;
cbControl.setAttribute("checkedCount", tmp);
}
console.log(cbControl.getAttribute("checkedCount"));
if(cbControl.getAttribute("checkedCount") == cbSubControls.length){ //这里有强制类型转换
cbControl.checked = true;
}
if(cbControl.getAttribute("checkedCount") == 0){
console.log("");
cbControl.checked = false;
}
}
}
}
</script>
</head>
<body>
<form id="my_form" action="" method="post">
<table>
<tr>
<td>
<input type="checkbox" id="cb_control"> 总开关
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="cb_sub_control"> 开关1
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="cb_sub_control"> 开关2
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="cb_sub_control"> 开关3
</td>
</tr>
</table>
</form>
</body>
</html>