<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>表格数据行全选/全不选/反选的示例</title>
<style>
table {
border: 1px solid;
width: 500px;
margin-left: 30%;
}
th, td {
text-align: center;
border: 1px solid;
}
div {
margin-top: 10px;
margin-left: 30%;
}
.over {
background-color: pink;
}
.out {
background-color: white;
}
</style>
<script !src="">
window.onload = function () {
document.getElementById("selectAll").onclick = function () {
var cbs = document.getElementsByName("cb");
for (let i = 0; i < cbs.length; i++) {
cbs[i].checked = true;
}
};
function setFirstCbStatus() {
var firstCb = document.getElementById("firstCb");
var cbs = document.getElementsByName("cb");
for (let i = 0; i < cbs.length; i++) {
if (cbs[i].checked == false && cbs[i].id != "firstCb") {
firstCb.checked = false;
break;
}
if (i == cbs.length - 1) {
firstCb.checked = true;
}
}
}
document.getElementById("selectRev").onclick = function () {
var cbs = document.getElementsByName("cb");
for (let i = 0; i < cbs.length; i++) {
if (cbs[i].id != "firstCb") {
cbs[i].checked = !cbs[i].checked;
}
}
setFirstCbStatus();
};
document.getElementById("firstCb").onclick = function () {
var cbs = document.getElementsByName("cb");
for (let i = 0; i < cbs.length; i++) {
cbs[i].checked = this.checked;
}
};
var cbs = document.getElementsByName("cb");
for (let i = 0; i < cbs.length; i++) {
if (cbs[i].id != "firstCb") {
cbs[i].onclick = setFirstCbStatus;
}
}
document.getElementById("unSelectAll").onclick = function () {
var cbs = document.getElementsByName("cb");
for (let i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
};
var trs = document.getElementsByTagName("tr");
for (let i = 0; i < trs.length; i++) {
trs[i].onmouseover = function () {
this.className = "over";
};
trs[i].onmouseout = function () {
this.className = "out";
};
}
};
</script>
</head>
<body>
<table>
<caption>学生信息表</caption>
<tr>
<th><input id="firstCb" type="checkbox" name="cb"></th>
<th>编号</th>
<th>姓名</th>
<th>性别</th>
<th>操作</th>
</tr>
<tr>
<td><input type="checkbox" name="cb"></td>
<td>1</td>
<td>令狐冲</td>
<td>男</td>
<td><a href="javascript:void(0);">删除</a></td>
</tr>
<tr>
<td><input type="checkbox" name="cb"></td>
<td>2</td>
<td>任我行</td>
<td>男</td>
<td><a href="javascript:void(0);">删除</a></td>
</tr>
<tr>
<td><input type="checkbox" name="cb"></td>
<td>3</td>
<td>岳不群</td>
<td>男</td>
<td><a href="javascript:void(0);">删除</a></td>
</tr>
<tr>
<td><input type="checkbox" name="cb"></td>
<td>4</td>
<td>周芷若</td>
<td>女</td>
<td><a href="javascript:void(0);">删除</a></td>
</tr>
</table>
<div>
<input id="selectAll" type="button" value="全选">
<input id="unSelectAll" type="button" value="全不选">
<input id="selectRev" type="button" value="反选">
</div>
</body>
</html>
|