学习笔记,仅供参考,有错必究
动态生成表格
从本地取到数据,动态生成表格,并添加删除操作.
代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
</head>
<body>
<table cellspacing="0">
<tr>
<th>姓名</th>
<th>科目</th>
<th>成绩</th>
<th>操作</th>
</tr>
</table>
<script>
var dataset = [
{name: '羊羊',
subject: '数据科学',
score: 99},
{name: '猪猪',
subject: '统计学',
score: 95},
{name: '猫猫',
subject: '最优化',
score: 100},
{name: '狗崽子',
subject: '可视化',
score: 59},
];
var tbody = document.querySelector("tbody");
for(var i = 0; i < dataset.length; i++) {
var tr = document.createElement("tr");
tbody.appendChild(tr);
for (var k in dataset[i]) {
var td = document.createElement("td");
td.innerHTML = dataset[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>
结果展示:
|