将数组对象动态生成表格
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>将数组对象动态生成表格</title>
<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;
}
thead tr:nth-of-type(1){
background-color: lightblue;
}
</style>
</head>
<body>
<table id="cart">
<caption>购物车</caption>
<thead>
<tr>
<td>编号</td>
<td>品名</td>
<td>数量</td>
<td>单价</td>
<td>总价</td>
</tr>
</thead>
<tbody></tbody>
</table>
<script>
var data=[
{id:1,name:'苹果',count:10,price:8,total:80},
{id:2,name:'香蕉',count:5,price:3,total:15},
{id:3,name:'橘子',count:10,price:5,total:50},
{id:4,name:'西瓜',count:20,price:8,total:160},
{id:5,name:'草莓',count:6,price:10,total:60}
];
//动态添加购物车内容
//获取购物车
var cart=document.getElementById('cart');
//获取tbody
var tbody=cart.tBodies[0];
//遍历数据data,并添加到tbody
for(var i=0;i<data.length;i++){
//创建行
var tr=document.createElement('tr');
//一行是一个对象
Object.keys(data[i]).forEach(function (key) {
tr.innerHTML+='<td>'+data[i][key]+'</td>';
});
//把行添加到tbody中
tbody.appendChild(tr);
}
</script>
</body>
</html>点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号