使用数组模拟学生数据
动态创建行
为单元格填充数据
提供删除链接,可删除所在的行
<table>
<thead>
<tr>
<th>姓名</th>
<th>科目</th>
<th>成绩</th>
<th>操作</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
//模拟数据,数组集合
let listData = [{
name: "张三",
subject: "JavaScript",
score: 100
}, {
name: "李四",
subject: "JavaScript",
score: 90
}, {
name: "王五",
subject: "JavaScript",
score: 90
}, ]
//获取到tbody控件,便于后边添加移除操作
let tbody = document.querySelector("tbody");
//遍历循环,添加行
for (let i = 0; i < listData.length; i++) {
//创建行元素
let tr = document.createElement("tr");
//添加行节点
tbody.appendChild(tr);
//遍历每组对象,添加每行单元格的添加
for (let value in listData[i]) {
let td = document.createElement("td");
td.innerHTML = listData[i][value];
// console.log(listData[i][value]);
tr.appendChild(td);
}
//创建单元格,添加删除标签
let del = document.createElement("td")
del.innerHTML = '<a href="javascript:;">删除</a>'
tr.appendChild(del)
}
//获取所有的a标签,添加点击事件进行删除
let as = document.querySelectorAll("a");
// for (let i = 0; i < as.length; i++) {
// console.log(as[i]);
// }
as.forEach(x => {
x.addEventListener("click", function() {
tbody.removeChild(this.parentNode.parentNode);
});
})
</script>