這段代碼哪里錯(cuò)了 為什么新添的元素刪不了?
<!DOCTYPE html>
<html>
?<head>
? <title> new document </title> ?
? <meta http-equiv="Content-Type" content="text/html; charset=gbk"/> ??
? <script type="text/javascript">?
? // 鼠標(biāo)移動(dòng)改變背景,可以通過給每行綁定鼠標(biāo)移上事件和鼠標(biāo)移除事件來改變所在行背景色。
? 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'};
? }
? } ? ?
? ? // 編寫一個(gè)函數(shù),供添加按鈕調(diào)用,動(dòng)態(tài)在表格的最后一行添加子節(jié)點(diǎn); ?
? ? ?var num=2;
? ? function add(){
? ? num++;
? ? var table=document.getElementById('table');
? ? var ntr=document.createElement('tr');
? ? var ntd1=document.createElement('td');
? ? var ntd2=document.createElement('td');
? ? var ntd3=document.createElement('td');
? ? var tx=document.createElement('input');
? ? var ta=document.createElement('a');
? ? tx.type='text';
? ? ta.innerHTML='刪除';
? ? ta.href='javascript:;'
? ? ta.onclick='del(this)'; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 這里修改成ta.setAttribute("onclick","del(this)”)為什么就沒問題了?
? ? if(num<10){ntd1.innerHTML='xh00'+num;}
? ? else if(num>=10&&num<100){ntd1.innerHTML='xh0'+num;}
? ? else{ntd1.innerHTML='xh'+num;}
? ? ntd2.appendChild(tx);
? ? ntd3.appendChild(ta);
? ? ntr.appendChild(ntd1);
? ? ntr.appendChild(ntd2);
? ? ntr.appendChild(ntd3);
? ? table.appendChild(ntr);
? ? 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'};
? }
? ? } ? ? ?
? ?// 創(chuàng)建刪除函數(shù)
? ? ? function del(obj){
? ? ? var tr=obj.parentNode.parentNode;
? ? ? tr.parentNode.removeChild(tr);
? ? ? }
這段代碼哪里錯(cuò)了 為什么新添的元素刪不了?
2017-04-12
ta.addEventListener('click',function(){this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode);})
這樣寫好像標(biāo)準(zhǔn) 但我想調(diào)用已有的應(yīng)該怎么辦?