分析了老师的代码才知道自己错在哪里了。 document.getElementById('table').lastChild; 原来对于 removeChild()方法的理解 都不太正确, 应该是 子节点列表中的节点调用此方法,同理 appendChild(). 对么?
<!DOCTYPE html>
<html>
<head>
<title> new document </title>
<meta charset="UTF-8">
<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:remove();" >删除</a></td> <!--在删除按钮上添加点击事件 -->
</tr>
<tr>
<td>xh002</td>
<td>刘小芳</td>
<td><a href="javascript:remove();" >删除</a></td> <!--在删除按钮上添加点击事件 -->
</tr>
</table>
<input type="button" value="添加一行" /> <!--在添加按钮上添加点击事件 -->
<script>
var table = document.getElementById("table");
var tr = table.getElementsByTagName("tr");
window.onload = function(){
//点击添加新行,开始
var but = document.getElementsByTagName("input")[0];
but.onclick = function(){
var newtr = document.createElement("tr");
var td1 = document.createElement("td");
var td2 = document.createElement("td");
var td3 = document.createElement("td");
td1.style.height = "20px";
newtr.appendChild(td1);
newtr.appendChild(td2);
newtr.appendChild(td3);
table.appendChild(newtr);
}
//鼠标经过变色;
for (var i=0;i<tr.length; i++){
tr[i].onmousemove = function(){
this.style.backgroundColor = "#f2f2f2"
};
tr[i].onmouseout = function(){
this.style.backgroundColor = "#fff";
}
}
}
// 删除当前行;
function remove(){
var a = table.getElementsByTagName("a");
for (var i=0;i<a.length;i++){
a[i].onclick = function(){
var parent = this.parentNode.parentNode;
var oldparent = parent.parentNode;
oldparent.removeChild(parent);
}
}
}
</script>
</body>
</html>JS dom中替换或者删除某个节点都需要通过这个节点的父节点来操作的
但是看老师第九章的练习代码:添加一行<tr>
var tab_node = document.getElementById('table').lastChild;
*****
tab_node.appendChild(new_node_tr);
table.lastChild ——应该就是 tr 了吧 ,然后用 tr 去 添加 tr. 就相当于就相当于 兄弟节点 添加了兄弟节点
我试过了 去掉 lastChild 但是发现 如果去掉之后 添加节点时没有问题的,但是删除节点的方法会有问题。
document.getElementById('table').lastChild 返回id为table的对象的最后一个子节点
<body>
<ul id="test">
<li>JavaScript</li>
<li>HTML</li>
</ul>
<script type="text/javascript">
var a = document.getElementById("test"); //把id为test的对象赋值给a
var b = document.createElement("li"); //在对象li的字节后添加一个新对象li
b.innerHTML="PHP"; //为空字节赋值
a .appendChild(b) //在a中添加一个新的子字节。a是li的父
</script>
</body>