請(qǐng)幫忙看下代碼,感覺(jué)沒(méi)問(wèn)題 但是就是實(shí)現(xiàn)不出來(lái)
<!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(){ ??var?tr=document.getElementsByTagName("tr"); ??for(i=0;i<=tr.length;i++){ tr[i].onmouseover=function(){ ??this.style.backgroundColor="#fcfcfc"; ?? } tr[i].onmouseout=function(){ this.style.backgroundColor="#fff"; } ??} //改變背景顏色 ?function?add(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='del(this)'>刪除</a>"; ?tr.appendChild(td);??? ? ?tbody.appendChild(tr);??? } //增加一行 ?function?del(obj){ ????var?tbody?=?document.getElementById('table').lastChild;?? var?tr?=?obj.parentNode.parentNode; tbody.removeChild(tr); ?} //刪除一行 ?? ?????//?鼠標(biāo)移動(dòng)改變背景,可以通過(guò)給每行綁定鼠標(biāo)移上事件和鼠標(biāo)移除事件來(lái)改變所在行背景色。 ????????? ????? ? ?} ????? ??????//?編寫(xiě)一個(gè)函數(shù),供添加按鈕調(diào)用,動(dòng)態(tài)在表格的最后一行添加子節(jié)點(diǎn); ????? ???? ??? ? ?????//?創(chuàng)建刪除函數(shù) ????? ??</script>? ?</head>? ?<body>? ???<table?border="1"?width="50%"?id="table"> ???<tr> <th>學(xué)號(hào)</th> <th>姓名</th> <th>操作</th> ???</tr>?? ???<tr> <td>xh001</td> <td>王小明</td> <td><a?href="javascript:;"??onClick="del(this)"?/>刪除</a></td>???<!--在刪除按鈕上添加點(diǎn)擊事件??--> ???</tr> ???<tr> <td>xh002</td> <td>劉小芳</td> <td><a?href="javascript:;"??onClick="del(this)"?/>刪除</a></td>???<!--在刪除按鈕上添加點(diǎn)擊事件??--> ???</tr>?? ???</table> ???<input?type="button"?value="添加一行"?onclick="add()"?/>???<!--在添加按鈕上添加點(diǎn)擊事件??--> ?</body> </html>
改變背景顏色沒(méi)問(wèn)題,就是增加一行 和刪除一行的代碼不對(duì)
2016-09-28
第10行:for循環(huán)判斷條件是<不是<=;
定義的function放在window.onload的function外面;
41行同樣的不是lastchild
2016-09-28
第21行,var?tbody?=?document.getElementById('table').lastChild; 新添加的tr應(yīng)該是加到table上的,不是加到lastchild上。改成var?tbody?=?document.getElementById('table')試一下。