JavaScript表格新增刪除
阿新 • • 發佈:2018-12-27
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <style> #div1 {width:100px; height:100px; background:red; position:absolute;} #div2 {width:100px; height:100px; background:yellow; position:absolute;} </style> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>無標題文件</title> <script> window.onload=function() { var oTab=document.getElementById('tab1'); var oBtn=document.getElementById('btn1'); var oTxt=document.getElementById('txt1'); //序號第幾個 var iNowId=oTab.tBodies[0].rows.length+1; oBtn.onclick=function() { //建立一個tr var oTr=document.createElement('tr'); var oTd=null; oTd=document.createElement('td'); oTd=innerHTML=iNowId++; oTr.appendChild(oTd); oTd=document.createElement(td); oTd.innerHTML=oTxt.value; oTr.appendChild(oTd); oTd=document.createElement('td'); oTd.innerHTML='<a href="javascript:;">刪除</a>'; oTr.appendChild(oTd); //刪除 oTd.getElementsByTagName('a')[0].onclick=function() { oTab.tBodies[0].removeChild(this.parentNode.parentNode); }; oTab.appendChild(oTr); }; } </script> </head> <body> <input id='txt1' type="text" /> <input id='btn1' type='button' value="新增" /> <table id="tab1" border="1" width="400"> <thead> <td>ID</td> <td>姓名</td> <td>操作</td> </thead> <tbody> <tr> <td>1</td> <td>blue</td> <td></td> </tr> <tr> <td>2</td> <td>Leo</td> <td></td> </tr> <tr> <td>3</td> <td>默默</td> <td></td> </tr> <tr> <td>4</td> <td>aaa</td> <td></td> </tr> <tr> <td>5</td> <td>bbb</td> <td></td> </tr> <tr> <td>6</td> <td>ccc</td> <td></td> </tr> </tbody> </table> </body> </html>