慕码人5330596
2019-03-25 03:53
<!DOCTYPE html>
<html>
<head>
<title> new document </title>
<meta http-equiv="Content-Type" content="text/html; charset=gbk"/>
<script type="text/javascript">
window.onload = function () {
changeBg();
};
function changeBg() {
// 鼠标移动改变背景,可以通过给每行绑定鼠标移上事件和鼠标移除事件来改变所在行背景色。
var trs = document.getElementsByTagName("tr"),
body = document.getElementsByTagName("body")[0];
for (var i = 0; i < trs.length; i++) {
trs[i].onmouseover = function () {
for (var j = 0; j < trs.length && j != i; j++) {
trs[j].style.background = "#fff";
}
this.style.background = "#ccc";
};
trs[i].onmouseout = function () {
this.style.background = "#fff";
}
}
}
// 编写一个函数,供添加按钮调用,动态在表格的最后一行添加子节点;
function addTable(){
var table = document.getElementById("table"),
newNode = document.createElement("tr"),
index = table.childNodes.length+1;
newNode.innerHTML = "<td>xh00"+ index +"</td><td></td><td><a href='javascript:;' onclick='removeTd(this)' >删除</a></td>";
table.appendChild(newNode);
changeBg();
}
// 创建删除函数
function removeTd(node) {
node.parentNode.parentNode.parentNode.removeChild(node.parentNode.parentNode);
}
</script>
</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="removeTd(this)">删除</a></td> <!--在删除按钮上添加点击事件 -->
</tr><tr>
<td>xh002</td>
<td>刘小芳</td>
<td><a href="javascript:;" onclick="removeTd(this)" >删除</a></td> <!--在删除按钮上添加点击事件 -->
</tr></table>
<input type="button" value="添加一行" onclick="addTable()"/> <!--在添加按钮上添加点击事件 -->
</body>
</html>如题,我的代码运行后,如果删除中间的行,再点“添加一行”,新添加行的学号会连不上。
感觉可以用正则来获取最后一行的学号,新行学号=最后行学号+1。js里是怎么使用正则呢。。。
同问,删除了第一行后,第二行的数字2怎么变成1
JavaScript进阶篇
469171 学习 · 22584 问题
相似问题