表格添加、删除
1 <!DOCTYPE HTML>
2 <html>
3 <head>
4 <meta charset="utf-8">
5 <title>无标题文档</title>
6 <script>
7 window.onload=function ()
8 {
9 var oTab=document.getElementById('tab1');
10
11 var oBtn=document.getElementById('btn1');
12 var oName=document.getElementById('name');
13 var oAge=document.getElementById('age');
14 var id=oTab.tBodies[0].rows.length+1;
15
16 oBtn.onclick=function ()
17 {
18 var oTr=document.createElement('tr');
19
20 var oTd=document.createElement('td');
21 oTd.innerHTML=id++; //?
22 oTr.appendChild(oTd);
23
24 var oTd=document.createElement('td');
25 oTd.innerHTML=oName.value;
26 oTr.appendChild(oTd);
27
28 var oTd=document.createElement('td');
29 oTd.innerHTML=oAge.value;
30 oTr.appendChild(oTd);
31
32 var oTd=document.createElement('td');
33 oTd.innerHTML='<a href="javascript:;">删除</a>';
34 oTr.appendChild(oTd);
35
36 oTd.getElementsByTagName('a')[0].onclick=function ()
37 {
38 oTab.tBodies[0].removeChild(this.parentNode.parentNode);
39 };
40
41 oTab.tBodies[0].appendChild(oTr);
42 };
43 };
44 </script>
45 </head>
46
47 <body>
48 姓名:<input id="name" type="text" />
49 年龄:<input id="age" type="text" />
50 <input id="btn1" type="button" value="添加" />
51 <table id="tab1" border="1" width="500">
52 <thead>
53 <td>ID</td>
54 <td>姓名</td>
55 <td>年龄</td>
56 <td>操作</td>
57 </thead>
58 <tbody>
59 <tr>
60 <td>1</td>
61 <td>Blue</td>
62 <td>27</td>
63 <td></td>
64 </tr>
65 <tr>
66 <td>2</td>
67 <td>张三</td>
68 <td>23</td>
69 <td></td>
70 </tr>
71 <tr>
72 <td>3</td>
73 <td>李四</td>
74 <td>28</td>
75 <td></td>
76 </tr>
77 <tr>
78 <td>4</td>
79 <td>王五</td>
80 <td>25</td>
81 <td></td>
82 </tr>
83 <tr>
84 <td>5</td>
85 <td>张伟</td>
86 <td>24</td>
87 <td></td>
88 </tr>
89 </tbody>
90 </table>
91 </body>
92 </html>