<!DOCTY
PE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>动态生成一张表格</title>
</head>
<style>
table,th,td{
border: 1px solid #666;
}
table {
width: 500px;
text-align: center;
border-collapse: collapse;
}
table caption {
font-size: 1.2rem;
margin-bottom: 15px;
}
/* 这里必须在nth-of-type(1)前添加父元素,否则thead,tbody中的第一行都会生效 */
thead tr:nth-of-type(1) {
background-color: lightblue;
}
</style>
<body>
<table id="cart">
<caption>购物车3</caption>
<thead>
<tr>
<th>编号</th>
<th>品名</th>
<th>数量</th>
<th>单价</th>
<th>操作</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script>
// 动态生成一个类数组对象
var data = [
{id: 1, name: '牛奶', count: 3, price: 50},
{id: 1, name: '苹果', count: 10, price: 80},
{id: 1, name: '衣服', count: 2, price: 600},
{id: 1, name: '牙刷', count: 2, price: 600},
{id: 1, name: '手机', count: 1, price: 9999}
];
//获取到table表单
var cart = document.getElementById('cart');
//获取到表单内容tbody
var tbody = cart.tBodies[0];
for (var i = 0; i < data.length; i++){
var tr = document.createElement('tr');
// 表格数据的第一行是一个对象,对象是根据属性名来访问
// 只要获取到属性名组成的数组,遍历一下这个对象就可以生成一行数据啦
Object.keys(data[i]).forEach(function (value) {
tr.innerHTML += '<td>' + data[i][value] + '</td>';
});
tr.innerHTML += '<td><button style="background-color: lime">编辑</button> <button style="background-color: red">删除</button></td>';
tbody.append(tr);
}
</script>
</body>
</html>