<!DOCTYPE?html>
<html>
<head>
<title>?new?document?</title>??
<meta?http-equiv="Content-Type"?content="text/html;?charset=utf-8"/>???
<script?type="text/javascript">?
window.onload?=?function(){
?????//?鼠標移動改變背景,可以通過給每行綁定鼠標移上事件和鼠標移除事件來改變所在行背景色。
?????var?fu_tr?=?document.getElementById("table").getElementsByTagName("tr");
?????for(var?i=0;?i<fu_tr.length;?i++){
????? fu_tr[i].onmouseover?=?function(){
????? this.style.background?=?"#cccccc";
????? };
????? fu_tr[i].onmouseout?=?function(){
????? this.style.background?=?"#ffffff";
????? };
?????}
?????
?}
??????//?編寫一個函數(shù),供添加按鈕調用,動態(tài)在表格的最后一行添加子節(jié)點;
??????function?adda(){
?????? var?tr?=?document.createElement("tr");
?????? var?fu?=?document.getElementById("table");
?????? var?fu_tr?=?document.getElementById("table").getElementsByTagName("tr")[1];
??????
?????? tr.innerHTML?=?fu_tr.innerHTML;
?????? console.log(tr);
?????? fu.appendChild(tr);
??????}
?????//?創(chuàng)建刪除函數(shù)
?????function?dela(a){
????? //var?fu?=?document.getElementById("table");
????? var?aa?=?a.parentNode.parentNode;
????? aa.parentNode.removeChild(aa);
?????}
?</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="dela(this);"?>刪除</a></td>???<!--在刪除按鈕上添加點擊事件??-->
</tr>
<tr>
<td>xh002</td>?
<td>劉小芳</td>
<td><a?href="javascript:;"?onclick="dela(this);"?>刪除</a></td>???<!--在刪除按鈕上添加點擊事件??-->
</tr>??
</table>
<input?type="button"?value="添加一行"?onclick="adda();"?/>???<!--在添加按鈕上添加點擊事件??-->
</body>
</html>
2017-02-26
因為你給添加的<tr>元素沒有添加鼠標移入和移除事件,如下:
tr.onmouseover= function(){
????????????? this.style.backgroundColor = "#ccc";
????????? };
tr.onmouseout= function(){
????????????? this.style.backgroundColor = "#fff";
????????? };
2017-02-26
buzhidao a?