无法删除节点
点击删除 控制台报错Cannot read property 'parentNode' of undefined at del
代码如下
<script type="text/javascript">
window.onload = function() {
var tr = document.getElementsByTagName("tr");
for (var i = 0; i < tr.length; i++) {
tr[i].onmouseover = function() {
this.style.backgroundColor = '#f2f2f2';
}
tr[i].onmouseout = function() {
this.style.backgroundColor = '#fff';
}
}
} //1. 鼠标移到不同行上时背景色改为色值为 #f2f2f2,移开鼠标时则恢复为原背景色 #fff
var num = 2;
function add() {
num++;
var tr = document.createElement("tr");
var xh = document.createElement("td");
var xm = document.createElement("td");
var del = document.createElement("td");
xh.innerHTML = "xh00" + num;
xm.innerHTML = "<input value='请输入姓名'/>"; //?
del.innerHTML = "<a href='javascript:del(this)'>删除</a>";
var table = document.getElementById("table");
table.appendChild(tr);
tr.appendChild(xh);
tr.appendChild(xm);
tr.appendChild(del);
//插入节点
var tr = document.getElementsByTagName("tr");
for (var i = 0; i < tr.length; i++) {
tr[i].onmouseover = function() {
this.style.backgroundColor = '#f2f2f2';
}
tr[i].onmouseout = function() {
this.style.backgroundColor = '#fff';
}
}
}
function del(obj){
var table = obj.parentNode.parentNode.parentNode;
var tr = obj.parentNode.parentNode;
table.removeChild(tr);
}
</script>
调用函数用的<a href="javascript:del(this);">删除</a>
我的理解是 obj是a标签 obj.parentNode是td
obj.parentNode.parentNode是tr
obj.parentNode.parentNode.parentNode是table
要删除table中的tr就是table.removeChild(tr);