JS中操作DOM文件
阿新 • • 發佈:2019-01-04
在前面示例中演示了使用DOM技術遍歷文件,在DOM中不僅可以通過節點的屬性查詢節點,還可以對節點進行建立、插入、刪除和替換等操作。這些操作都是通過節點(Node)物件提供的方法來完成。Node物件的常用方法如下:
下面用一個示例,操作DOM文件,實現新增評論和刪除評論功能:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>遍歷文件</title> <script language="JavaScript"> //新增評論 function addComment() { var person = document.createTextNode(form1.person.value); var content = document.createTextNode(form1.content.value); var td_person = document.createElement("td"); var td_content = document.createElement("td"); var tr = document.createElement("tr"); var tbody = document.createElement("tbody"); td_person.appendChild(person); td_content.appendChild(content); tr.appendChild(td_person); tr.appendChild(td_content); tbody.appendChild(tr); var tComment = document.getElementById("comment"); tComment.appendChild(tbody);//將節點tbody加入表格節點尾部 form1.person.value = ""; form1.content.value = ""; } //刪除第一條評論 function delFirstComment(){ var tComment=document.getElementById("comment"); if(tComment.rows.length>1){ tComment.deleteRow(1); } } //刪除最後一條評論 function delLastComment(){ var tComment=document.getElementById("comment"); if(tComment.rows.length>1){ tComment.deleteRow(tComment.rows.length-1) } } </script> </head> <body> <table width="600" border="1" align="center" cellpadding="0" bordercolor="#FFFFFF" bordercolorlight="#666666" bordercolordark="#FFFFFF" id="comment"> <tr> <td width="18%" height="27" align="center" bgcolor="#E5BB93">評論人</td> <td width="82%" height="27" align="center" bgcolor="#E5BB93">評論內容</td> </tr> </table> <form name="form1" method="post" action=""> 評論人:<input name="person" type="text" id="person" size="40" /> <br> 評論內容: <textarea name="content" cols="60" rows="6" id="content"></textarea> </form> <input name="Button" type="button" class="btn_grey" value="發表" onclick="addComment()"> <input name="Reset" type="button" class="btn_grey" value="重置"> <input name="Button" type="button" class="btn_grey" value="刪除第一條評論" onclick="delFirstComment()"> <input name="Button" type="button" class="btn_grey" value="刪除最後一條評論" onclick="delLastComment()"> </body> </html>