1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8" />
5 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6 <title>Document</title>
7 <style>
8 table {
9 500px;
10 border: 1px solid #eeeeee;
11 text-align: center;
12 }
13 thead {
14 background-color: orange;
15 }
16 td {
17 border: 1px solid #eeeeee;
18 }
19 </style>
20 </head>
21 <body>
22 <div class="box">
23 <label for="">姓名</label><input id="name" type="text" /><br />
24 <label for="">科目</label><input id="score" type="text" /><br />
25 <label for="">成绩</label><input id="subject" type="text" />
26 <button>提交</button>
27 </div>
28 <table cellspacing="0" ; cellpadding="0">
29 <thead>
30 <tr>
31 <th>姓名</th>
32 <th>科目</th>
33 <th>成绩</th>
34 <th>操作</th>
35 </tr>
36 </thead>
37 <tbody></tbody>
38 </table>
39 <script>
40 var tbody = document.querySelector('tbody')
41 var btn = document.querySelector('button')
42 var obj = {}
43 var data = [
44 {
45 name: '张三',
46 subject: 'javascript',
47 score: 80,
48 },
49 ]
50 //添加点击添加事件
51 btn.onclick = function () {
52 var name = document.querySelector('#name')
53 var score = document.querySelector('#score')
54 var subject = document.querySelector('#subject')
55 var tr = document.createElement('tr')
56 tbody.appendChild(tr)
57 var td1 = document.createElement('td')
58 var td2 = document.createElement('td')
59 var td3 = document.createElement('td')
60 var td4 = document.createElement('td')
61 tr.appendChild(td1)
62 tr.appendChild(td2)
63 tr.appendChild(td3)
64 tr.appendChild(td4)
65 td1.innerHTML = name.value
66 td2.innerHTML = score.value
67 td3.innerHTML = subject.value
68 td4.innerHTML = '<a href ="javascript:;">删除</a>'
69 //将输入的数据保存到集合中
70 obj.name = name.value
71 obj.subject = subject.value
72 obj.score = score.value
73 //将集合中的数据推到数组中去;
74 data.push(obj)
75 //清空输入框中的数据;
76 name.value = ''
77 score.value = ''
78 subject.value = ''
79 //添加后,调用删除函数,自动循环获取每个a标签的数量
80 del()
81 }
82 //读取data中的数据
83 for (var i = 0; i < data.length; i++) {
84 var tr = document.createElement('tr')
85 tbody.appendChild(tr)
86 //读取数组中,每个集合中的数据
87 for (var k in data[i]) {
88 var td = document.createElement('td')
89 td.innerHTML = data[i][k]
90 tr.appendChild(td)
91 }
92 var td = document.createElement('td')
93 tr.appendChild(td)
94 td.innerHTML = '<a href = "javascript:;">删除</a>'
95 //调用删除函数,循环获取每个a标签的数量
96 del()
97 }
98 //删除函数封装
99 function del() {
100 var as = tbody.querySelectorAll('a')
101 for (let i = 0; i < as.length; i++) {
102 as[i].onclick = function () {
103 tbody.removeChild(this.parentNode.parentNode)
104 }
105 }
106 }
107 </script>
108 </body>
109 </html>
时间如白驹过隙,忽然而已,且行且珍惜......