添加的不能刪除什么鬼?
<!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(){
? ? ? ? ? ? ? ? ??
? ? ? //鼠標(biāo)移動(dòng)改變背景,可以通過給每行綁定鼠標(biāo)移上事件和鼠標(biāo)移除事件來改變所在行背景色。
? ? ? ? ?var tr_arr = document.getElementsByTagName("tr");
for(i=0;i<tr_arr.length;i++){
//tr_arr[i].onmouseover=function(){this.style.backgroundColor='red';}
//tr_arr[i].onmouseout=function(){this.style.backgroundColor='white';}
tr_arr[i].setAttribute("onmouseover","this.style.backgroundColor='red'");
tr_arr[i].setAttribute("onmouseout","this.style.backgroundColor='white'");
}
}
? ? ?
? ? ? // 編寫一個(gè)函數(shù),供添加按鈕調(diào)用,動(dòng)態(tài)在表格的最后一行添加子節(jié)點(diǎn);
? function appendNoed(){
var tabNode = document.getElementById("table");
var trNode = document.createElement("tr");
var appA = document.createElement("a");
for(i=1;i<=3;i++){
//alert("循環(huán)"+i+"次");
trNode.appendChild(document.createElement("td"));
if(i==3){
trNode.lastChild.appendChild(appA);
var a= trNode.lastChild.firstChild;
a.innerHTML="刪除";
a.onClick="del(this)";
a.href="javascript:;";
}
}
tabNode.appendChild(trNode);
? ? }
? ? ?
? ? ?// 創(chuàng)建刪除函數(shù)
function del(x){
alert(x.id);
? ? ? var trNode = x.parentNode.parentNode;
? ? ? var tabNode = x.parentNode.parentNode.parentNode;
? tabNode.removeChild(trNode);
? ? }
? </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="appendNoed()" />? ?<!--在添加按鈕上添加點(diǎn)擊事件? -->
?</body>
</html>
2018-06-11
你的<a>標(biāo)簽添加onclick屬性未成功,建議如下:
原代碼:
改為:
2018-06-11
同上一個(gè)? ?新加的tr是需要加到tbody 中的
2018-06-08
?a.innerHTML="<a href='javascript:;' onclick='del(this)'>刪除</a>";
你需要吧a.innerHTML里面的這樣寫