標籤:head body orm create 增加 ddb log onload text
<html><title>動態處理表格式資料</title> <head> <script type="text/javascript"> function clearForm(){ document.getElementById("deptno").value=""; document.getElementById("dname").value=""; } window.onload=function(){ document.getElementById("addBtn").addEventListener("click",onloadData,false); } function onloadData(){ var deptno=document.getElementById("deptno").value; var dname=document.getElementById("dname").value; addRow(deptno,dname); clearForm(); } //刪除:找到父元素,調用其removeChild("指定刪除的元素") function removeRow(deptno){ var deptRow=document.getElementById("dept-"+deptno); var dept=document.getElementById("dept-body"); dept.removeChild(deptRow); } function addRow(deptno,dname){ var trElt=document.createElement("tr"); trElt.setAttribute("id","dept-"+deptno);//設定tr的屬性 var deptnoTd=document.createElement("td"); var dnameTd=document.createElement("td"); var delTd=document.createElement("td"); var delBtn=document.createElement("button");//建立button按鈕 delBtn.appendChild(document.createTextNode("刪除"));//追加文本資料 delBtn.addEventListener("click",function(){//添加事件 removeRow(deptno); },false); delTd.appendChild(delBtn); deptnoTd.appendChild(document.createTextNode(deptno)); dnameTd.appendChild(document.createTextNode(dname)); trElt.appendChild(deptnoTd); trElt.appendChild(dnameTd); trElt.appendChild(delTd); document.getElementById("dept-body").appendChild(trElt); } </script> </head> <body> <div> 部門編號:<input type="text" name="deptno" id="deptno"/><br> 部門名稱:<input type="text" name="dname" id="dname"/><br> <input type="button" value="增加" id="addBtn"/> <input type="button" value="清空" onclick="clearForm()"/> </div> <div> <table border="1" width="80%"> <thead > <tr> <td>部門編號</td> <td>部門名稱</td> <td>操作</td> </tr> </thead> <tbody id="dept-body"> </tbody> </table> </div> </body></html>
JavaScript操作DOM(動態表格處理)