实现要求:
- 点击"全选"框,以下所有选项全部勾选。
- 把"全选"框从选中状态勾选成未选中状态,其他复选框全部取消选中效果。
- 当其他复选框全部选中,"全选框"为选中状态。
- 当其他复选框有一个未选中,"全选框"取消选中状态。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function myAll(){
var all = document.getElementById('all');
var oneList = document.getElementsByName('one');
for(var i = 0; i < oneList.length; i++){
oneList[i].checked = all.checked;
}
}
function myOne(){
var all = document.getElementById('all');
var oneList = document.getElementsByName('one');
for(var i = 0; i < oneList.length; i++){
if(oneList[i].checked == false){
all.checked = false;
return;
}
}
all.checked=true;
}
</script>
</head>
<body>
<table id="myTable" border="1" cellpadding="0" cellspacing="0" width="90%" height="180px">
<tr>
<th>全选<input id="all" type="checkbox" onclick="myAll()"/>
</th> <th>序号</th>
<th>名称</th>
<th>单价</th>
<th>数量</th>
<th>总计</th> </tr>
</tr>
<tr>
<td><input name="one" type="checkbox" onclick="myOne()"/></td>
<td>1</td>
<td>嘟嘟喵</td>
<td>¥125</td>
<td>1</td>
<td>¥125</td>
</tr>
<tr>
<td><input name="one" type="checkbox" onclick="myOne()"/></td>
<td>1</td>
<td>蜡笔小新</td>
<td>¥125</td>
<td>1</td>
<td>¥125</td>
</tr>
<tr>
<td><input name="one" type="checkbox" onclick="myOne()"/></td>
<td>1</td>
<td>咸蛋超人</td>
<td>¥125</td>
<td>1</td>
<td>¥125</td>
</tr>
</table>
</body>
</html>
当点击全选按钮,下方三个按钮都会被选中:
当下方的按钮有一个被再次点击取消选中时,全选按钮也会取消选中: