如果我增加一行,我的onmouseover在新的一行就會不好使,該怎么辦呢?
<!DOCTYPE html>
<html>
?<head>
? <title> new document </title> ?
? <meta charset="utf-8"/> ??
? <script type="text/javascript">?
??
?
? ? window.onload = function(){
? ? var tr=document.getElementsByTagName("tr");
? ? for(var i=0;i<tr.length;i++){
? ? tr[i].onmouseover=function(){
? ? this.style.backgroundColor="#f2f2f2";
? ? }
? ? tr[i].onmouseout=function(){
? ? this.style.backgroundColor="#fff";
? ? }
? ? }
}
? ? ?
? ? ? // 編寫一個函數(shù),供添加按鈕調(diào)用,動態(tài)在表格的最后一行添加子節(jié)點(diǎn);
? ? ?function addClass(){
? ? ? var table=document.getElementById("table");
? ? ? var tr=document.createElement("tr");
? ? ? var td1=document.createElement("td");
? ? ? var td2=document.createElement("td");
? ? ? td1.innerHTML=prompt("請輸入學(xué)號");
? ? ? td2.innerHTML=prompt("請輸入姓名");
? ? ? table.appendChild(tr);
? ? ? tr.appendChild(td1);
? ? ? tr.appendChild(td2);
? ? ? var td3=document.createElement("td");
? ? ? var a=document.createElement("a");
? ? ? a.innerHTML="刪除";
? ? ? a.setAttribute("onclick","del(this)")
? ? ? td3.appendChild(a);
? ? ? tr.appendChild(td3);
? ? ?}
? ?
? ? ?
? ? ?// 創(chuàng)建刪除函數(shù)
? ? ?function del(obj){
? ? ? var tr=obj.parentNode.parentNode;
? ? ? ? ?tr.parentNode.removeChild(tr);
? ? ?}
? </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 onclick="del(this);" >刪除</a></td> ? <!--在刪除按鈕上添加點(diǎn)擊事件 ?-->
? </tr>
? <tr>
<td>xh002</td>
<td>劉小芳</td>
<td><a onclick="del(this);" >刪除</a></td> ? <!--在刪除按鈕上添加點(diǎn)擊事件 ?-->
? </tr> ?
? </table>
? <input type="button" value="添加一行" ?onclick="addClass()"/> ? <!--在添加按鈕上添加點(diǎn)擊事件 ?-->
?</body>
</html>
2018-07-27
這個少了window.onload剛開始沒這個效果噢?
2018-06-11
事件委托
2018-05-24
我這樣弄是可以實(shí)現(xiàn)你要的效果 但不知道是不是最好的方法 你可以參考一下。