<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
table {
width: 500px;
margin: 100px auto;
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>
</tbody>
</table>
<script>
var dates = [{
name: '魏璎珞',
subject: 'JavaScript',
score: 100
}, {
name: '弘历',
subject: 'JavaScript',
score: 98
}, {
name: '傅恒',
subject: 'JavaScript',
score: 99
}, {
name: '明玉',
subject: 'JavaScript',
score: 88
}, {
name: '大猪蹄子',
subject: 'JavaScript',
score: 0
}]
//创建行,有几个人就有几行
var tbody = document.querySelector('tbody');
for (var i = 0; i < dates.length; i++) {
//创建
var tr = document.createElement('tr');
//添加
tbody.appendChild(tr);
//创建单元格td 个数取决于对象包含的属性数
for (var j in dates[i]) {
//创建单元格
var td = document.createElement('td');
// for(var k in obj) {
// k 得到的是属性名
// obj[k] 得到是属性值
// }
// 把对象里面的属性值dates[i][j] 给td
td.innerHTML = dates[i][j];
//添加单元格
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() {
//要删除的父级.removeChild(要删除的内容)
tbody.removeChild(this.parentNode.parentNode);
}
}
</script>
</body>
</html>
js动态生成表格
最新推荐文章于 2022-09-26 16:49:40 发布