全选和单选
案例分析
-
全选和取消全选做法:让下面所有的复选框的checked属性(选中状态)跟随全选按钮即可
-
当单选全部勾选的时候,全选的选框自动勾选,当失去个别单选选框的时候,全选选框失去勾选
在全选和取消全选的代码中,使用的是this.checked
,而不使用flag来标记,这样子代码更精简,如果使用flag,那么可能会使用两个for循环
<!DOCTYPE html>
<html>
<head>
<title>全选和单选</title>
</head>
<body>
<table border="1">
<thead>
<tr>
<th><input type="checkbox" name="choseAll" id="choseAll"></th>
<th>商品</th>
<th>价格</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" name="goodList"></td>
<td>商品1</td>
<td class="price">1000</td>
</tr>
<tr>
<td><input type="checkbox" name="goodList"></td>
<td>商品2</td>
<td class="price">20000</td>
</tr>
<tr>
<td><input type="checkbox" name="goodList"></td>
<td>商品3</td>
<td class="price">100</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
var chose_all = document.getElementById('choseAll');
var inputList = document.getElementsByName('goodList');
var price = document.querySelectorAll('.price');
var submit = document.querySelector('button');
//全选或者取消全选
chose_all.onclick = function(){
for (let i = 0; i < inputList.length; i++) {
inputList[i].checked = this.checked;
}
}
//单选对全选的影响
flag = false;
for (let i = 0; i < inputList.length; i++) {
inputList[i].onclick = function(){
for (let i = 0; i < inputList.length; i++) {
if(inputList[i].checked == true){
flag = true;
}else{
flag = false;
break;
}
}
chose_all.checked = flag;
}
}
</script>
</body>
</html>