關(guān)于刪除按鈕,為什么只能刪除新增的,確不能刪除原有的兩條數(shù)據(jù)
<!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)改變背景,可以通過(guò)給每行綁定鼠標(biāo)移上事件和鼠標(biāo)移除事件來(lái)改變所在行背景色。
???????? var trs = document.getElementsByTagName("tr");
?? ??? ? for(var i = 0; i < trs.length;i++){
?? ??? ????? backGd(trs[i]);
?? ??? ? }
?? ? }
??? ?
???? function backGd(obj){
???????? obj.onmouseover = function(){
???????????? this.style.backgroundColor = "#f2f2f2";
???????? }
???????? obj.onmouseout = function(){
???????????? this.style.backgroundColor = "#fff";
???????? }
???? }
??? ?
???? function add(){
??????? var table = document.getElementById("table");
??????? var tr = document.createElement("tr");
??????? var td0 = document.createElement("td");
??????? var td1 = document.createElement("td");
??????? var td2 = document.createElement("td");
??????? var trlength = document.getElementsByTagName("tr").length;
??????? td0.innerHTML = "xh" + getNum(trlength);
??????? td1.innerHTML = "同學(xué)"+trlength;
??????? td2.innerHTML = "<a href='javascript:;' onclick='delRow(this)'>刪除</a>";
??????? backGd(tr);
??????? tr.appendChild(td0);
??????? tr.appendChild(td1);
??????? tr.appendChild(td2);
??????? table.appendChild(tr);
???? }
??? ?
???? function getNum(num){
???????? if(num < 10){
???????????? return "00"+num;
???????? }else if(num < 100){
???????????? return "0"+num;
???????? }else{
???????????? return num;
???????? }
???? }?? ??? ?
? ??? ?
???? // 創(chuàng)建刪除函數(shù)
???? function delRow(obj){
???????? var parents = obj.parentNode.parentNode;
???????? var table = document.getElementById("table");
???????? table.removeChild(parents);
???? }
? </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="delRow(this)">刪除</a></td>?? <!--在刪除按鈕上添加點(diǎn)擊事件? -->
?? ??? </tr>
?? ??? <tr>
?? ??? ?<td>xh002</td>
?? ??? ?<td>劉小芳</td>
?? ??? ?<td><a href="javascript:;" onclick="delRow(this)">刪除</a></td>?? <!--在刪除按鈕上添加點(diǎn)擊事件? -->
?? ??? </tr> ?
?? ??? </table>
?? ??? <input type="button" value="添加一行" onclick="javascript:add()"/>?? <!--在添加按鈕上添加點(diǎn)擊事件? -->
?</body>
</html>
2016-05-26
因?yàn)閠able被瀏覽器讀的時(shí)候默認(rèn)添加了個(gè)叫tbody的子元素,新增加的tr在tbody外面,而原有2條tr在tbody里面,執(zhí)行刪除時(shí),刪除table子元素tr失敗了,因?yàn)樵衪r是tbody的子元素,這里執(zhí)行報(bào)錯(cuò),所以沒(méi)有反應(yīng)
2016-06-07
那怎么弄才能刪除原來(lái)那兩個(gè)呢?具體怎么實(shí)現(xiàn)?求教?。?/p>