需求:
(界面稍微有点难看,但是可以自己任意修改,这里面就弄一个简陋的)
1. 全选、反选、全不选按钮对应实现其字面功能
2. 点删除会删除对应行
3. 鼠标停放在对应列上时,该行bg-color会变成粉红色,如下图:
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>表格选中</title>
<style>
div{
text-align: center;
margin:50px;
}
input{
box-sizing:border-box;
padding-left: 4px;
padding-top:4px;
}
table{
border: 1px solid;
margin: auto;
width:500px;
}
th,td{
border:1px solid;
text-align: center;
}
#select{
margin-top: 15px;
margin-left:-300px;
}
.out{
background-color: white;
}
.over{
background-color: pink;
}
</style>
<script>
window.onload=function () {
//全选按钮
var select_all = document.getElementById("select_all");
select_all.onclick=function () {
//1.获取所有的checkbox选择框
var cbs = document.getElementsByName("cb");
//2.遍历获得的数组,使每一个元素为true
for (var i=0;i<cbs.length;i++){
cbs[i].checked=true;
}
}
//全不选按钮
var select_none = document.getElementById("select_none");
select_none.onclick=function () {
//1.获取所有的checkbox选择框
var cbs = document.getElementsByName("cb");
//2.遍历获得的数组,使每一个元素为false
for (var i=0;i<cbs.length;i++){
cbs[i].checked=false;
}
}
//反选按钮
var invert_select = document.getElementById("invert_select");
invert_select.onclick=function () {
//1.获取所有的checkbox选择框
var cbs = document.getElementsByName("cb");
//2.遍历获得的数组,使每一个元素为false
for (var i=0;i<cbs.length;i++){
if (cbs[i].checked)cbs[i].checked=false;
else
cbs[i].checked=true;
}
}
//给所有tr标签绑定事件,onmouseover和onmouseout
var trs = document.getElementsByTagName("tr");
for (var i=0;i<trs.length;i++){
//移到元素之上所做出的事件
trs[i].onmouseover=function () {
this.className="over";
}
trs[i].onmouseout=function () {
this.className="out";
}
}
}
//删除方法
function del(obj) {
var table=obj.parentNode.parentNode.parentNode;
var tr=obj.parentNode.parentNode;
table.removeChild(tr);
}
</script>
</head>
<body>
<table id="table">
<caption>学生信息表</caption>
<tr>
<td></td>
<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);" onclick="del(this);">删除</a></td>
</tr>
<tr>
<td><input type="checkbox" name="cb"></td>
<td>2</td>
<td>李四</td>
<td>男</td>
<td><a href="javascript:void(0);" onclick="del(this);">删除</a></td>
</tr>
<tr>
<td><input type="checkbox" name="cb"></td>
<td>3</td>
<td>王二麻子</td>
<td>男</td>
<td><a href="javascript:void(0);" onclick="del(this);">删除</a></td>
</tr>
</table>
<div id="select">
<input type="button" id="select_all" value="全选">
<input type="button" id="select_none" value="全不选">
<input type="button" id="invert_select" value="反选">
</div>
</body>
</html>