<!--這是我最后修改完成后可以正常運行的代碼,雖然代碼可以正常運行了,但我還是有個疑惑,就是不論是插入表格行"tr"還是刪除表格行"tr",都要將"table"的子節點作為父節點進行操作才能正常運行,可從HTML代碼中來看,"table"不就是"tr"的父節點嗎?難道中間還隱藏著什么節點,既是"tr"的父節點,又是"table"的子節點?-->
<!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(){
?????????Highlight();
??????}
?????//?鼠標移動改變背景,可以通過給每行綁定鼠標移上事件和鼠標移除事件來改變所在行背景色。
??????function?Highlight(){
????????var?tbody?=?document.getElementById("table").lastChild;
????????var?row?=?tbody.getElementsByTagName("tr");
for(var?i=1;i<row.length;i++){
???? ??row[i].onmouseover?=?function(){
???? ????this.style.backgroundColor?="#3fc";
}
??row[i].onmouseout?=?function(){
????????????this.style.backgroundColor?="#fff";
}
????????}
??}
?????
??????//?編寫一個函數,供添加按鈕調用,動態在表格的最后一行添加子節點;
????function?add(){
????????var?newNode?=?document.createElement("tr");
????????var?child1?=?document.createElement("td");
????????var?child2?=?document.createElement("td");
????????var?child3?=?document.createElement("td");
????????child1.innerHTML?=?"<input?/>";
????????child2.innerHTML?=?"<input?/>";
????????child3.innerHTML?=?"<a?href='javascript:;'?onclick='del(this)'>刪除</a>";
????????newNode.appendChild(child1);
????????newNode.appendChild(child2);
????????newNode.appendChild(child3);
????????document.getElementById("table").lastChild.appendChild(newNode);
????????Highlight();
????}
?????//?創建刪除函數
????function?del(obj){
????????var?fatherNode?=?document.getElementById("table").lastChild;
????????fatherNode.removeChild(obj.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="del(this)"?>刪除</a></td>???<!--在刪除按鈕上添加點擊事件??-->
???</tr>
???<tr>
<td>xh002</td>
<td>劉小芳</td>
<td><a?href="javascript:;"?onclick="del(this)"?>刪除</a></td>???<!--在刪除按鈕上添加點擊事件??-->
???</tr>??
???</table>
???<input?type="button"?value="添加一行"?onclick="add()"?/>???<!--在添加按鈕上添加點擊事件??-->
?</body>
</html>“.lastChild”都是根據答案后加的,結果加完之后就能正常運行了,問題肯定出在“看不見的節點”上。
關于《JavaScript進階篇》第九章編程練習的問題
NodeOS
2016-02-29 21:16:00