js添加和刪除節點, 方法調用是通過子節點中的節點來添加的呢。
分析了老師的代碼才知道自己錯在哪里了。 ?document.getElementById('table').lastChild; ? ?原來對于 ?removeChild()方法的理解 都不太正確, 應該是 子節點列表中的節點調用此方法,同理 appendChild(). ?對么?
分析了老師的代碼才知道自己錯在哪里了。 ?document.getElementById('table').lastChild; ? ?原來對于 ?removeChild()方法的理解 都不太正確, 應該是 子節點列表中的節點調用此方法,同理 appendChild(). ?對么?
2017-03-26
舉報
2017-03-29
<!DOCTYPE?html> <html> ?<head> ??<title>?new?document?</title>?? ??<meta?charset="UTF-8"> ??<meta?http-equiv="Content-Type"?content="text/html;?charset=gbk"/>???? ?</head>? ?<body>? ???<table?border="1"?width="50%"?id="table"> ???<tr> <th>學號</th> <th>姓名</th> <th>操作</th> ???</tr>?? ???<tr> <td>xh001</td> <td>王小明</td> <td><a?href="javascript:remove();"?>刪除</a></td>???<!--在刪除按鈕上添加點擊事件??--> ???</tr> ???<tr> <td>xh002</td> <td>劉小芳</td> <td><a?href="javascript:remove();"?>刪除</a></td>???<!--在刪除按鈕上添加點擊事件??--> ???</tr>?? ???</table> ???<input?type="button"?value="添加一行"??/>???<!--在添加按鈕上添加點擊事件??--> ??????<script> ??????var?table?=?document.getElementById("table"); ????????var?tr?=?table.getElementsByTagName("tr"); ??????window.onload?=?function(){ ?????? //點擊添加新行,開始 ?????? ???var?but?=?document.getElementsByTagName("input")[0]; ?????? ???but.onclick?=?function(){ ?????? ??? var?newtr?=?document.createElement("tr"); ?????? ??? var?td1?=?document.createElement("td"); ?????? ??? var?td2?=?document.createElement("td"); ?????? ??? var?td3?=?document.createElement("td"); ?????? ??? td1.style.height?=?"20px"; ?????? ??? newtr.appendChild(td1); ?????? ??? newtr.appendChild(td2); ?????? ??? newtr.appendChild(td3); ?????? ??? table.appendChild(newtr); ?????? ???} ?????? ???//鼠標經過變色; ???????for?(var?i=0;i<tr.length;?i++){ ???????? tr[i].onmousemove?=?function(){ ???????? this.style.backgroundColor?=?"#f2f2f2" ???????? }; ???????? tr[i].onmouseout?=?function(){ ???????? this.style.backgroundColor?=?"#fff"; ???????? } ????????} ????} ??????//?刪除當前行; ????function?remove(){ ???? var?a?=?table.getElementsByTagName("a"); ???? for?(var?i=0;i<a.length;i++){ ???? a[i].onclick?=?function(){ ???? var?parent?=?this.parentNode.parentNode; ???? var?oldparent?=?parent.parentNode; ???? oldparent.removeChild(parent); ???? } ???? } ????} ??? ????? ??</script>? ?</body> </html>JS dom中替換或者刪除某個節點都需要通過這個節點的父節點來操作的
2017-03-27
但是看老師第九章的練習代碼:添加一行<tr>
var tab_node = document.getElementById('table').lastChild;
*****
tab_node.appendChild(new_node_tr);
table.lastChild? ——應該就是 tr 了吧 ,然后用 tr? 去 添加 tr.?? 就相當于就相當于 兄弟節點 添加了兄弟節點
我試過了 去掉 lastChild 但是發現 如果去掉之后 添加節點時沒有問題的,但是刪除節點的方法會有問題。
2017-03-27
document.getElementById('table').lastChild ?返回id為table的對象的最后一個子節點
<body>
<ul id="test">
? <li>JavaScript</li>
? <li>HTML</li>
</ul>?
?
<script type="text/javascript">
? var a = document.getElementById("test"); ? ?????? ?//把id為test的對象賦值給a
? var b = document.createElement("li");????????? ? //在對象li的字節后添加一個新對象li?
? ? b.innerHTML="PHP"; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //為空字節賦值
? a .appendChild(b) ? ? ? ? ? ? ? ??????????????//在a中添加一個新的子字節。a是li的父
</script>?
</body>