JS全选及单选复选框
程序员文章站
2022-05-09 13:06:42
...
问题:
1.点击全选,复选框全部选中;取消全选,复选框
2.复选框有一个没选中,全选框的√取消;
代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>全选单选</title>
<style>
* {
padding: 0;
margin: 0;
}
.wrap {
width: 300px;
margin: 100px auto 0;
}
table {
border-collapse: collapse;
border-spacing: 0;
border: 1px solid #c0c0c0;
width: 300px;
}
th,
td {
border: 1px solid #d0d0d0;
color: #404060;
padding: 10px;
}
th {
background-color: #09c;
font: bold 16px "微软雅黑";
color: #fff;
}
td {
font: 14px "微软雅黑";
}
tbody tr {
background-color: #f0f0f0;
}
tbody tr:hover {
cursor: pointer;
background-color: #fafafa;
}
</style>
</head>
<body>
<div class="wrap">
<table>
<thead>
<tr>
<th>
<input type="checkbox" id="j_cbAll" />
</th>
<th>商品</th>
<th>价钱</th>
</tr>
</thead>
<tbody id="j_tb">
<tr>
<td>
<input type="checkbox" />
</td>
<td>iPhone8</td>
<td>8000</td>
</tr>
<tr>
<td>
<input type="checkbox" />
</td>
<td>iPad Pro</td>
<td>5000</td>
</tr>
<tr>
<td>
<input type="checkbox" />
</td>
<td>iPad Air</td>
<td>2000</td>
</tr>
<tr>
<td>
<input type="checkbox" />
</td>
<td>Apple Watch</td>
<td>2000</td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript">
var j_cbAll = document.getElementById("j_cbAll");
var j_tb = document.querySelectorAll("#j_tb input")
//全选
j_cbAll.onclick = function() {
for (var i = 0; i < j_tb.length; i++) {
j_tb[i].checked = this.checked;
}
}
//单选
for (var i = 0; i < j_tb.length; i++) {
j_tb[i].onclick = function() {
var flag = true;
for (var i = 0; i < j_tb.length; i++) {
if(!j_tb[i].checked) {
flag = false;
break;
}
}
j_cbAll.checked = flag;
}
}
</script>
</body>
</html>
运行结果:
上一篇: 有关色光的文章推荐10篇