參考答案代碼問題
<!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>學(xué)號</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>
我認(rèn)為這段代碼中的addOne()函數(shù)中的var tbody = document.getElementById('table').lastChild; 與后面的tbody.appendChild(tr);相矛盾 (其中,tbody應(yīng)該為<table>中的最后一個<tr>;而函數(shù)tbody.appendChild(tr);是將新的<tr>元素加到tbody中最后一個子節(jié)點(diǎn)的后面,也就是說將新的<tr>元素加到了最后一個<tr>元素中的最后一個<td>元素的后面,這不就產(chǎn)生矛盾了么。),我認(rèn)為應(yīng)該要將document.getElementById('table').lastChild;中的lastChild去掉。
2016-12-09
這個是因?yàn)?lt;table>標(biāo)簽在其下有thead,tbody,tfoot.三個子節(jié)點(diǎn),在不設(shè)置的時候,tbody是會默認(rèn)的。所以說document.getElementById('table').lastChild 其實(shí)是指tbody這個節(jié)點(diǎn),然后tbody.appendChild(tr)就不矛盾了。