关于删除按钮,为什么只能删除新增的,确不能删除原有的两条数据
<!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(){
// 鼠标移动改变背景,可以通过给每行绑定鼠标移上事件和鼠标移除事件来改变所在行背景色。
var trs = document.getElementsByTagName("tr");
for(var i = 0; i < trs.length;i++){
backGd(trs[i]);
}
}
function backGd(obj){
obj.onmouseover = function(){
this.style.backgroundColor = "#f2f2f2";
}
obj.onmouseout = function(){
this.style.backgroundColor = "#fff";
}
}
function add(){
var table = document.getElementById("table");
var tr = document.createElement("tr");
var td0 = document.createElement("td");
var td1 = document.createElement("td");
var td2 = document.createElement("td");
var trlength = document.getElementsByTagName("tr").length;
td0.innerHTML = "xh" + getNum(trlength);
td1.innerHTML = "同学"+trlength;
td2.innerHTML = "<a href='javascript:;' onclick='delRow(this)'>删除</a>";
backGd(tr);
tr.appendChild(td0);
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);
}
function getNum(num){
if(num < 10){
return "00"+num;
}else if(num < 100){
return "0"+num;
}else{
return num;
}
}
// 创建删除函数
function delRow(obj){
var parents = obj.parentNode.parentNode;
var table = document.getElementById("table");
table.removeChild(parents);
}
</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="delRow(this)">删除</a></td> <!--在删除按钮上添加点击事件 -->
</tr>
<tr>
<td>xh002</td>
<td>刘小芳</td>
<td><a href="javascript:;" onclick="delRow(this)">删除</a></td> <!--在删除按钮上添加点击事件 -->
</tr>
</table>
<input type="button" value="添加一行" onclick="javascript:add()"/> <!--在添加按钮上添加点击事件 -->
</body>
</html>