為什么在刪除的時(shí)候會(huì)出現(xiàn) Uncaught TypeError: Cannot read property 'parentNode' of undefined
<!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 tagname1? ?=? ? document.getElementsByTagName("tr")
? ? ?// 鼠標(biāo)移動(dòng)改變背景,可以通過(guò)給每行綁定鼠標(biāo)移上事件和鼠標(biāo)移除事件來(lái)改變所在行背景色。
? ? ? ? for(var i=0;i<tagname1.length;i++)
{
colorchange(tagname1[i]);
}
}
? ? ?function colorchange(obj){
? ? obj.onmouseover=function(){
? ? obj.style.backgroundColor = "#f2f2f2";
? ? }
? ? obj.onmouseout=function(){
? ? obj.style.backgroundColor = "#fff";
? ? }
}
? ? ?
? ? ? // 編寫(xiě)一個(gè)函數(shù),供添加按鈕調(diào)用,動(dòng)態(tài)在表格的最后一行添加子節(jié)點(diǎn);
? ? ?var num=2;
? ? ?function add(){
? ? ?
? ? ? ? var tr1 = document.createElement("tr");
? ? ? ? var xh? = document.createElement("td");
? ? ? ? var xm? = document.createElement("td");
? ? ? ? var cz? = document.createElement("td");
? ? ? ? xh.innerHTML = "xh00"+ ++num;
? ? ? ? xm.innerHTML = xh.innerHTML+"人";
? ? ? ? cz.innerHTML = "<a href = 'javascript:deletelast(this)'>刪除</a>"
? ? ? ? var tab = document.getElementById("table");
? ? ? ? tab.appendChild(tr1);
? ? ? ? tr1.appendChild(xh);
? ? ? ? tr1.appendChild(xm);
? ? ? ? tr1.appendChild(cz);
? ? ? ? var tagname2 = document.getElementsByTagName("tr");
? ? ? ? for(var i=0;i<tagname2.length;i++){
? ? ? ? colorchange(tagname2[i]);
? ? ? ? }
? ? ?}
? ?
? ? ?
? ? ?// 創(chuàng)建刪除函數(shù)
? ? ?function deletelast(obj){
? ? ? ? ?var table = document.getElementById('table').lastChild;
? ? ? ? ? ? var tr = obj.parentNode.parentNode;
? ? ? ? ? ? table.removeChild(tr);
? ? ?}
? </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:deletelast(this);" >刪除</a></td>? ?<!--在刪除按鈕上添加點(diǎn)擊事件? -->
? ?</tr>
? ?<tr>
<td>xh002</td>
<td>劉小芳</td>
<td><a href="javascript:deletelast(this);" >刪除</a></td>? ?<!--在刪除按鈕上添加點(diǎn)擊事件? -->
? ?</tr>??
? ?</table>
? ?<input type="button" value="添加一行" onclick="add()" />? ?<!--在添加按鈕上添加點(diǎn)擊事件? -->
?</body>
</html>
2018-10-06
function deletelast(obj){
? ? ? ? ?var table = document.getElementById('table').lastChild;
? ? ? ? ? ? var tr = obj.parentNode.parentNode;
? ? ? ? ? ? table.removeChild(tr);
? ? ?}
你的刪除函數(shù)里table指的是“table”標(biāo)簽的最后一個(gè)子節(jié)點(diǎn),實(shí)際上也是一個(gè)“tr"標(biāo)簽,而removeChild是刪除子節(jié)點(diǎn),你的table和tr是同級(jí)的tr標(biāo)簽,所以會(huì)出錯(cuò)