<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>2.JS动态将数组添加到表格</title>
<style>
table, th, td{
border: 1px solid red;
}
table{
width: 400px;
text-align: center;
border-collapse: collapse;
}
table caption{
font-size: 1.4rem;
margin-bottom: 10px;
}
thead tr:nth-of-type(1){
background: lightblue;
}
</style>
</head>
<body>
<table id="cart">
<caption>购物车</caption>
<thead>
<tr>
<th>订单号</th>
<th>品名</th>
<th>数量</th>
<th>单价</th>
</tr>
</thead>
<tbody></tbody>
</table>
</body>
</html>
<script>
//第一步:创建一个购物车数组
var data = [
{id:2019012001,name:'牛奶',count:120,price:200},
{id:2019012002,name:'香蕉',count:180,price:109},
{id:2019012003,name:'面包',count:150,price:110}
];
// 第二步:获取table列表并用forEach写入到列表中
var cart = document.getElementById('cart');
var tbody = cart.children[2];
data.forEach(function(value){
//console.log(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>';
// 上面第二个tr开始要追加方式" += "否则会覆盖
tbody.appendChild(tr);
});
</script>点击 "运行实例" 按钮查看在线实例

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