功能实现没什么问题,只不过。。。进行多次删除操作的时候console控制台会报错,然而还是能正常删除该行。。。解决方案是把deleteLine函数从deleteList函数中移出来。。。可是。。。为什么移出来进行删除操作就不报错了呢。。。。VM2307:51 Uncaught TypeError: Cannot read property 'removeChild' of null提示错误在this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode);这行。<!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:;" >删除</a></td> <!--在删除按钮上添加点击事件 -->
</tr>
<tr>
<td>xh002</td>
<td>刘小芳</td>
<td><a href="javascript:;" >删除</a></td> <!--在删除按钮上添加点击事件 -->
</tr>
</table>
<input type="button" value="添加一行" id="add"/> <!--在添加按钮上添加点击事件 -->
<script>
var add = document.getElementById("add");
var tbodyEle = document.querySelector("tbody");
var allTr = document.querySelectorAll("tr");
var trLen = allTr.length;
var allA = document.querySelectorAll("a");
var aLen = allA.length;
function addLine (){
var trEle = document.createElement("tr");
var tdOne = document.createElement("td");
tdOne.innerHTML = "xh00" + (aLen + 1);
var tdTwo = document.createElement("td");
tdTwo.innerHTML = "逗比" + (aLen + 1) + "号";
var tdThr = document.createElement("td");
tdThr.innerHTML = "<a href='javascript:;' >删除</a>";
trEle.appendChild(tdOne);
trEle.appendChild(tdTwo);
trEle.appendChild(tdThr);
tbodyEle.appendChild(trEle);
//每次添加一行更新tr和a节点。并为新添加的行绑定hover和delete事件
allTr = document.querySelectorAll("tr");
allA = document.querySelectorAll("a");
trLen++; aLen++;
console.log(allTr);console.log(allA);console.log(trLen);
hover();
deleteList();
}
add.addEventListener("click", addLine);
function hover(){
for(var i = 0;i < trLen; i++){
allTr[i].addEventListener("mouseover", function(){this.style.backgroundColor = "#f2f2f2";});
allTr[i].addEventListener("mouseout", function(){this.style.backgroundColor = "#fff";});
}
}
hover();
function deleteList(){
function deleteLine(){
//每次删除一行更新tr和a节点。
this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode);
allTr = document.querySelectorAll("tr");
allA = document.querySelectorAll("a");
aLen--;trLen--;
console.log(allTr);console.log(allA);console.log(trLen);
}
for(var i = 0; i < aLen; i++){
allA[i].addEventListener("click", deleteLine);
}
}
deleteList();
</script>
</body>
</html>
添加回答
举报
0/150
提交
取消