练习4:表格效果

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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
#data {
border-collapse: collapse;
}
#data td, #data th {
width: 120px;
height: 40px;
text-align: center;
border: 1px solid black;
}
#buttons {
margin: 10px 0;
}
</style>
</head>
<body>
<table id="data">
<caption>数据统计表</caption>
<tbody>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>身高</th>
<th>体重</th>
</tr>
<tr>
<td>Item1</td>
<td>Item2</td>
<td>Item3</td>
<td>Item4</td>
<td>Item5</td>
</tr>
<tr>
<td>Item1</td>
<td>Item2</td>
<td>Item3</td>
<td>Item4</td>
<td>Item5</td>
</tr>
<tr>
<td>Item1</td>
<td>Item2</td>
<td>Item3</td>
<td>Item4</td>
<td>Item5</td>
</tr>
<tr>
<td>Item1</td>
<td>Item2</td>
<td>Item3</td>
<td>Item4</td>
<td>Item5</td>
</tr>
<tr>
<td>Item1</td>
<td>Item2</td>
<td>Item3</td>
<td>Item4</td>
<td>Item5</td>
</tr>
<tr>
<td>Item1</td>
<td>Item2</td>
<td>Item3</td>
<td>Item4</td>
<td>Item5</td>
</tr>
</tbody>
</table>
<div id="buttons">
<button id="pretty">隔行换色</button>
<button id="clear">清除数据</button>
<button id="remove">删单元格</button>
<button id="hide">隐藏表格</button>
</div>
<script src="js/mylib.js"></script>
<script>
function prettify() {
var trs = document.querySelectorAll('#data tr');
for (var i = 1; i < trs.length; i += 1) {
trs[i].style.backgroundColor =
i % 2 == 0 ? 'lightgray' : 'lightsteelblue';
}
}

function clear() {
var tds = document.querySelectorAll('#data td');
for (var i = 0; i < tds.length; i += 1) {
tds[i].textContent = '';
}
}

function removeLastRow() {
var table = document.getElementById('data');
if (table.rows.length > 1) {
table.deleteRow(table.rows.length - 1);
}
}

function hideTable() {
var table = document.getElementById('data');
table.style.visibility = 'hidden';
}

+function() {
var prettyBtn = document.querySelector('#pretty');
prettyBtn.addEventListener('click', prettify)
var clearBtn = document.querySelector('#clear');
clearBtn.addEventListener('click', clear);
var removeBtn = document.querySelector('#remove');
removeBtn.addEventListener('click', removeLastRow);
var hideBtn = document.querySelector('#hide');
hideBtn.addEventListener('click', hideTable);
}();
</script>
</body>
</html>