亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

參考答案代碼問題

<!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去掉。

正在回答

1 回答

這個是因為<table>標簽在其下有thead,tbody,tfoot.三個子節點,在不設置的時候,tbody是會默認的。所以說document.getElementById('table').lastChild 其實是指tbody這個節點,然后tbody.appendChild(tr)就不矛盾了。

0 回復 有任何疑惑可以回復我~
#1

qq_苔上雪_04205930

document.getElementById('table')的子節點就一個 所以firstChid和lastChild或者document.getElementById('table')[0],都是指的tbody節點
2016-12-09 回復 有任何疑惑可以回復我~

舉報

0/150
提交
取消
JavaScript進階篇
  • 參與學習       468832    人
  • 解答問題       22582    個

本課程從如何插入JS代碼開始,帶您進入網頁動態交互世界

進入課程

參考答案代碼問題

我要回答 關注問題
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號