Blogger Information
Blog 63
fans 1
comment 0
visits 75896
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
将数组对象动态生成表格
桃儿的博客
Original
1042 people have browsed it

将数组对象动态生成表格


实例

<!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>

运行实例 »

点击 "运行实例" 按钮查看在线实例


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post