1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>动态表格</title> 6 <style> 7 table{ 8 border: 1px solid; 9 margin: auto; 10 width: 500px; 11 } 12 td,th{ 13 text-align: center; 14 border: 1px solid; 15 } 16 div{ 17 text-align: center; 18 margin: 50px; 19 } 20 </style> 21 </head> 22 <body> 23 <div> 24 <input type="text" id="id" placeholder="请输入编号"> 25 <input type="text" id="name" placeholder="请输入姓名"> 26 <input type="text" id="gender" placeholder="请输入性别"> 27 <input type="button" id="btn_add" value="添加"> 28 </div> 29 30 <table> 31 <caption>学生信息表</caption> 32 <tr> 33 <th>编号</th> 34 <th>姓名</th> 35 <th>性别</th> 36 <th>操作</th> 37 </tr> 38 <tr> 39 <td>1</td> 40 <td>令狐冲</td> 41 <td>男</td> 42 <td><a href="javascript:void(0);" onclick="delTr(this);">删除</a> </td> 43 </tr> 44 45 <tr> 46 <td>2</td> 47 <td>任我行</td> 48 <td>男</td> 49 <td><a href="javascript:void(0);" onclick="delTr(this);">删除</a></td> 50 </tr> 51 52 <tr> 53 <td>3</td> 54 <td>岳不群</td> 55 <td>?</td> 56 <td><a href="javascript:void(0);" onclick="delTr(this);" >删除</a></td> 57 </tr> 58 </table> 59 60 <script> 61 62 document.getElementById("btn_add").onclick=function () { 63 var id=document.getElementById("id").value; 64 var name=document.getElementById("name").value; 65 var gender=document.getElementById("gender").value; 66 67 var table=document.getElementsByTagName("table")[0]; 68 69 //追加一行 70 table.innerHTML+="<tr>\n"+ 71 "<td>"+id+"</td>\n"+ 72 "<td>"+name+"</td>\n"+ 73 "<td>"+gender+"</td>\n"+ 74 "<td> <a href='javascript:void(0);' onclick='delTr(this);'>删除</a></td>\n"+ 75 "</tr>"; 76 } 77 function delTr (obj) { 78 var table=obj.parentNode.parentNode.parentNode; 79 var tr=obj.parentNode.parentNode; 80 table.removeChild(tr); 81 82 } 83 </script> 84 </body> 85 </html>