批改状态:合格
老师批语:
<!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>动态生成表格</title>
<style>
table,td,th{
border:1px solid red;
}
table{
width:500px;
border-collapse: collapse;
text-align: center;
}
table caption {
font-size: 1.2rem;
margin-bottom: 15px;
}
thead:nth-of-type(1){
background-color: aquamarine;
}
</style>
</head>
<body>
<table id = "cart2">
<caption>购物车1</caption>
<thead>
<tr>
<th>编号</th>
<th>品名</th>
<th>数量</th>
<th>单价</th>
</tr>
<tbody>
</tbody>
</thead>
</table>
<script>
var data = [
{id:1, name:'牛奶', count:3,price:50},
{id:2, name:'苹果', count:10,price:80},
{id:1, name:'衣服', count:2,price:600},
];
var cart2 = document.getElementById('cart2');
var tbody = cart2.children[2];//返回tbody
//遍历对象数组
data.forEach(function(value){
var tr = document.createElement('tr');
tr.innerHTML = '<td>' + value.id + '</td>';
tr.innerHTML += '<td>' + value.name + '</td>';
tr.innerHTML += '<td>' + value.count + '</td>';
tr.innerHTML += '<td>' + value.price + '</td>';
tbody.appendChild(tr);
})
</script>
</body>
</html>点击 "运行实例" 按钮查看在线实例

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号