1.实现效果:
准备好数据,刷新后加载数据。点击删除按钮后,删除数据。
2.代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>动态生成表格</title>
<style>
td {
border: 1px solid black;
width: 100px;
height: 30px;
line-height: 30px;
text-align: center;
}
th {
border: 1px solid black;
width: 100px;
height: 30px;
line-height: 30px;
text-align: center;
background-color:lavender;
}
table {
border: 1px solid black;
}
</style>
</head>
<body>
<table cellspacing="0">
<thead>
<tr>
<th>姓名</th>
<th>科目</th>
<th>成绩</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<!-- <tr>
<td>魏璎珞</th>
<td>JavaScript</th>
<td>100</td>
<td><a href="#">删除</a></td>
</tr>
<tr>
<td>魏璎珞</th>
<td>JavaScript</th>
<td>100</td>
<td><a href="#">删除</a></td>
</tr>
<tr>
<td>魏璎珞</th>
<td>JavaScript</th>
<td>100</td>
<td><a href="#">删除</a></td>
</tr>
<tr>
<td>魏璎珞</th>
<td>JavaScript</th>
<td>100</td>
<td><a href="#">删除</a></td>
</tr> -->
</tbody>
</table>
<script>
// 1.准备数据。
var data = [{
name:'张三',
subject: 'JavaScript',
score:100
},{
name:'李四',
subject: 'JavaScript',
score:99
},{
name:'王五',
subject: 'JavaScript',
score:78
}];
var tbody = document.querySelector('tbody');
for(var i = 0; i<data.length;i++) {
var tr = document.createElement('tr');
// var td1 = document.createElement('td');
// td1.innerHTML = data[i].name;
// var td2 = document.createElement('td');
// td2.innerHTML = data[i].subject;
// var td3 = document.createElement('td');
// td3.innerHTML = data[i].score;
// 可以用for循环来创建表格。
for(var k in data[i]) { //k是属性名,data[i][k]才是属性值
var td = document.createElement('td');
td.innerHTML = data[i][k];
tr.appendChild(td);
}
var td4 = document.createElement('td');
td4.innerHTML = '<a href="#">删除</a>';
tr.appendChild(td4);
tbody.appendChild(tr);
}
var as = document.querySelectorAll('a');
for(var i = 0; i<as.length; i++) {
as[i].onclick = function() {
// 不需要先删除td,再删除tr,直接删除tr即可。
tbody.removeChild(this.parentNode.parentNode);
}
}
</script>
</body>
</html>