本文實例為大家分享了js動態(tài)生成表格的具體代碼,供大家參考,具體內(nèi)容如下
針對DOM節(jié)點操作,該案例效果圖如下(代碼量不多,就沒有結構與行為相分離):
原生js實現(xiàn)(注釋里面解釋了做法):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
|
<!DOCTYPE html> < html > < head > < meta charset = "utf-8" > < title ></ title > < style type = "text/css" > table { width: 500px; margin: 100px auto; border-collapse: collapse; text-align: center; } td, th { border: 1px solid #333; } thead tr { height: 40px; background-color: #ccc; } </ style > </ head > < body > < table cellspacing = "0" > < thead > < tr > < th >姓名</ th > < th >科目</ th > < th >成績</ th > < th >操作</ th > </ tr > </ thead > < tbody > </ tbody > </ table > </ body > < script type = "text/javascript" > //因為里面的學生數(shù)據(jù)都是動態(tài)的,我們需要js動態(tài)生成 這里我們需要模擬數(shù)據(jù),自己定義好數(shù)據(jù) // 數(shù)據(jù)我們采取對象形式儲存 //1 先準備好學生的數(shù)據(jù) //2 所有數(shù)據(jù)都是放到tbody里面(多少人,多少行) var datas = [{ name: '劉舒新', subject: 'JavaScript', score: '100' }, { name: '宋祥隆', subject: 'JavaScript', score: '80' }, { name: '崔健', subject: 'JavaScript', score: '90' }, { name: '郄海淼', subject: 'JavaScript', score: '70' } ]; //console.log(datas.length); var tbody = document.querySelector('tbody'); for (var i = 0; i < datas.length ; i++) { //創(chuàng)建行 trs = document .createElement('tr'); tbody.appendChild(trs); //創(chuàng)建單元格 td的數(shù)量取決于每個對象里面的屬性個數(shù) for(var k in datas[i]){ //創(chuàng)建單元格 var td = document .createElement('td'); //把對象里面的屬性值 給td //console.log(datas[i][k]); td.innerHTML = datas [i][k]; trs.appendChild(td); } //創(chuàng)建操作刪除單元格 var td = document .createElement('td'); td.innerHTML='<a href = "javascript:;" rel = "external nofollow" >刪除</ a >' trs.appendChild(td); } //刪除操作 var a=document.querySelectorAll('a'); for(var i=0;i< a.length ;i++){ a[i] .onclick = function (){ tbody.removeChild(this.parentNode.parentNode); } } </script> </ html > |
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/weixin_47339511/article/details/112212948