参考大佬的,欢迎大佬持续优化
<!DOCTYPE html>
<html>
<head>
<title> 表格练习 </title>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
<style>
html,
body,
div,
table,
tr,
th,
td,
input {
margin: 0;
padding: 0;
}
a {
text-decoration: none;
color: #ff7474;
font-size: 14px;
display: block;
width: 60px;
margin: 0 auto;
}
button {
width: 160px;
line-height: 40px;
text-align: center;
margin: 0 auto;
display: block;
background-color: #ff4081;
color: #fff;
border: none;
border-radius: 3px;
outline: none;
}
table {
width: 600px;
margin: 50px auto;
table-layout: fixed;
border-collapse: collapse;
text-align: center;
line-height: 40px;
border: 1px solid #e2e2e2;
}
tr:nth-child(2n+1) {
background-color: #f7f7f7;
}
table tr:first-child {
background-color: #f7f7f7 !important;
}
table .active {
background-color: #e0f1ff;
}
th,
td {
border:1px solid #ccc;
}
tr{
border:1px solid #ccc;
}
th {
color: #333;
font-size: 14px;
}
td {
color: #666;
font-size: 14px;
}
</style>
<script type="text/javascript">
var changeColor;
var tables;
//页面初始化加载
window.onload = function () {
// 鼠标移动改变背景,可以通过给每行绑定鼠标移上事件和鼠标移除事件来改变所在行背景色。
tables = document.querySelector("#table");
changeColor = function () {
var tr1 = document.getElementsByTagName("tr");
for (var i = 1; i < tr1.length; i++) {
tr1[i].onmouseover = function () {
this.classList.add("active");
}
tr1[i].onmouseout = function () {
this.classList.remove("active");
}
}
}
changeColor();
}
// 编写一个函数,供添加按钮调用,动态在表格的最后一行添加子节点;
function add() {
var tbody = tables.childNodes[1]; //得到tbody节点
var trNode = document.createElement("tr"); //创建tr节点
tbody.appendChild(trNode); //将tr节点加入tbody
var num = parseInt(Math.random()*10);
trNode.innerHTML = '<td>xh00'+num + '</td><td>' + prompt("请输入名字") + '</td><td class="del"><a href="javascript:;" onclick="removes(this)">删除</a></td>';
changeColor();
}
// 创建删除函数
function removes(obj) {
//获取table子节点tbody然后在删除指定节点
// console.log(tables.childNodes[1])
tables.childNodes[1].removeChild(obj.parentNode.parentNode);
}
</script>
</head>
<body>
<table width="50%" id="table">
<tr>
<th>学号</th>
<th>姓名</th>
<th>操作</th>
</tr>
<tr>
<td>xh001</td>
<td>王小明</td>
<td><a href="javascript:;" onclick="removes(this)">删除</a></td>
<!--在删除按钮上添加点击事件 -->
</tr>
<tr>
<td>xh002</td>
<td>刘小芳</td>
<td><a href="javascript:;" onclick="removes(this)">删除</a></td>
<!--在删除按钮上添加点击事件 -->
</tr>
</table>
<button type="button" id="btn" onclick="add()">添加一行</button>
<!--在添加按钮上添加点击事件-->
</body>
</html>