<!DOCTYPE html>
<html>
<head>
<title> new document </title>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
</head>
<body>
<table border="1" width="50%" id="table">
<tr >
<th>学号</th>
<th>姓名</th>
<th>操作</th>
</tr>
<tr>
<td>xh001</td>
<td>王小明</td>
<td><a href="javascript:;" onclick="remove(this)">删除</a></td>
<!--在删除按钮上添加点击事件 -->
</tr>
<tr>
<td>xh002</td>
<td>刘小芳</td>
<td><a href="javascript:;" onclick="remove(this)">删除</a></td>
<!--在删除按钮上添加点击事件 -->
</tr>
</table>
<input id="num" type="text" placeholder="学号">
<input id="name" type="text" placeholder="姓名">
<input type="button" value="添加一行" onclick="append()" />
<!--在添加按钮上添加点击事件 -->
<script type="text/javascript">
var RootNode = document.getElementById('table');
function getbgColor(obj) {
obj.setAttribute("style", "background-color:#f2f2f2");
}
function delbgColor(obj) {
obj.setAttribute("style", "");
}
function xuanran() {
var trList = document.getElementsByTagName("tr");
for (var i = 0; i < trList.length; i++) {
// console.log(trList[i].getAttribute(onmouseover))
// if (trList[i].getAttribute(onmouseover) == null && trList[i].getAttribute(onmouseout) == null) {
trList[i].setAttribute("onmouseover", "getbgColor(this)");
trList[i].setAttribute("onmouseout", "delbgColor(this)");
// }
}
}
window.onload = function () {
// 鼠标移动改变背景,可以通过给每行绑定鼠标移上事件和鼠标移除事件来改变所在行背景色。
xuanran();
}
RootNode.childNodes[1].childNodes[0].setAttribute("onmouseover", "getbgColor()");
console.log(RootNode.childNodes[1].childNodes[0]);
// 编写一个函数,供添加按钮调用,动态在表格的最后一行添加子节点;
function createElement(type) {
return document.createElement(type);
}
function getInfo() {
let info = [];
info[0] = document.getElementById("num").value;
info[1] = document.getElementById("name").value;
return info;
}
function append() {
var Fnode = RootNode.childNodes[1];
info = getInfo();
var tr = createElement("tr");
var td1 = createElement("td");
var td2 = createElement("td");
var td3 = createElement("td");
var a = createElement("a");
a.setAttribute("href", "javascript:");
a.setAttribute("onclick", "remove(this)")
a.appendChild(document.createTextNode("删除"));
td1.appendChild(document.createTextNode(info[0]));
td2.appendChild(document.createTextNode(info[1]));
td3.appendChild(a);
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
Fnode.appendChild(tr);
xuanran();
};
// 创建删除函数
function remove(obj) {
var Fnode = RootNode.childNodes[1];
// console.log(Fnode.childNodes[0]);
Fnode.removeChild(obj.parentNode.parentNode);
}
</script>
</body>
</html>