參考答案代碼問題
<!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?addOne(obj){?
????????var?tbody?=?document.getElementById('table').lastChild;??
????????var?tr?=?document.createElement('tr');??
?????????
?????????var?td?=?document.createElement("td");
?????????td.innerHTML?=?"<input?type='text'/>";
?????????tr.appendChild(td);
?????????
?????????td?=?document.createElement("td");?????
?????????td.innerHTML?=?"<input?type='text'/>";
?????????tr.appendChild(td);
?????????
?????????td?=?document.createElement("td");????
?????????td.innerHTML?=?"<a?href='javascript:;'?onclick='deleteRow(this)'>刪除</a>";
?????????tr.appendChild(td);???
?????????
?????????tbody.appendChild(tr);???
????????Highlight();
????????}
?????function?deleteRow(obj){
????????var?tbody?=?document.getElementById('table').lastChild;??
????????var?tr?=?obj.parentNode.parentNode;
?????????tbody.removeChild(tr);
?????}
?????function?Highlight(){
????????var?tbody?=?document.getElementById('table').lastChild;????
????????trs?=?tbody.getElementsByTagName('tr');???
????????for(var?i?=1;i<trs.length;i++){
????????????trs[i].onmouseover?=?function(){
????????????????this.style.backgroundColor?="#f2f2f2";
????????????}?
????????????trs[i].onmouseout?=?function(){
????????????????this.style.backgroundColor?="#fff";
????????????}?
????????}??
?????}
??</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="deleteRow(this)">刪除</a></td>
???????</tr>
???????<tr>
????????<td>xh002</td>
????????<td>劉小芳</td>
????????<td><a?href="javascript:;"?onclick="deleteRow(this)">刪除</a></td>
???????</tr>??
???????</table>
???????<input?type="button"?value="添加一行"?onclick="addOne()"?/>
?</body>
</html>我認為這段代碼中的addOne()函數中的var tbody = document.getElementById('table').lastChild; 與后面的tbody.appendChild(tr);相矛盾 (其中,tbody應該為<table>中的最后一個<tr>;而函數tbody.appendChild(tr);是將新的<tr>元素加到tbody中最后一個子節點的后面,也就是說將新的<tr>元素加到了最后一個<tr>元素中的最后一個<td>元素的后面,這不就產生矛盾了么。),我認為應該要將document.getElementById('table').lastChild;中的lastChild去掉。
2016-12-09
這個是因為<table>標簽在其下有thead,tbody,tfoot.三個子節點,在不設置的時候,tbody是會默認的。所以說document.getElementById('table').lastChild 其實是指tbody這個節點,然后tbody.appendChild(tr)就不矛盾了。