請幫忙看下代碼,感覺沒問題 但是就是實現不出來
<!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); ?} //刪除一行 ?? ?????//?鼠標移動改變背景,可以通過給每行綁定鼠標移上事件和鼠標移除事件來改變所在行背景色。 ????????? ????? ? ?} ????? ??????//?編寫一個函數,供添加按鈕調用,動態在表格的最后一行添加子節點; ????? ???? ??? ? ?????//?創建刪除函數 ????? ??</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>
改變背景顏色沒問題,就是增加一行 和刪除一行的代碼不對
2016-09-28
第10行:for循環判斷條件是<不是<=;
定義的function放在window.onload的function外面;
41行同樣的不是lastchild
2016-09-28
第21行,var?tbody?=?document.getElementById('table').lastChild; 新添加的tr應該是加到table上的,不是加到lastchild上。改成var?tbody?=?document.getElementById('table')試一下。