<title>案例实现:动态生成表格</title>
<style>
a {
text-decoration: none;
}
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>
<!-- 表格数据动态生成 -->
<!-- <tr>
<td></td>
</tr> -->
</tbody>
</table>
<script>
var datas = [{
// 角色
name: '闻人翊悬',
// 法术
magic: '火系',
// 法力
mana: 85
}, {
name: '申屠子夜',
magic: '水系',
mana: 80
}, {
name: '公仪楚人',
magic: '土系',
mana: 85
}, {
name: '容成墨熙',
magic: '木系',
mana: 90
}, {
name: '轩辕神君',
magic: '金系',
mana: 100
}, {
name: '小新',
magic: '童系',
mana: 100
}];
var tbody = document.querySelector('tbody');
for (var i = 0; i < datas.length; i++) {
var tr = document.createElement('tr');
tbody.appendChild(tr);
for (var k in datas[i]) {
var td = document.createElement('td');
td.innerHTML = datas[i][k];
tr.appendChild(td);
}
var td = document.createElement('td');
td.innerHTML = '<a href="JavaScript:;">删除</a>';
tr.appendChild(td);
var as = document.querySelectorAll('a');
for (var i = 0; i < as.length; i++) {
as[i].onclick = function() {
tbody.removeChild(this.parentNode.parentNode);
}
}
}
</script>
</body>
</html>
运行结果