Blogger Information
Blog 5
fans 0
comment 0
visits 3305
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
使用JS将数据显示到表格中(时间:2019.01.17)
Less的作业
Original
1302 people have browsed it

实例

<!DOCTYPE html>
<html lang = "en">
<head>
    <meta charset = "UTF-8">
    <title>使用JS将数据显示到表格中</title>
    <style>
        table {
            width: 500px;
        }
        
        table, th, td {
            border: 1px solid #DDDDDD;
            /*collapse ke`laps  坍方*/
            border-collapse: collapse;
            text-align: center;
        }
        
        thead {
            background-color: lightblue;
        }
        
        table caption {
            font-size: 1.2em;
            margin-bottom: 15px;
        }
    </style>
</head>
<body>
<div>
    <table>
        <caption>购物车</caption>
        <thead>
        <tr>
            <th>序号</th>
            <th>商品名称</th>
            <th>数量</th>
            <th>单价</th>
        </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</div>
<script>
    //模拟数据库取出来的数据
    var data = [
        {id: 1, name: '牛奶', count: 16, price: 40},
        {id: 2, name: '瓜子', count: 2, price: 15},
        {id: 3, name: '鸡翅', count: 2, price: 30},
        {id: 4, name: '水蜜桃', count: 3, price: 6}
    ];
    // 数据展示在表格中
    // table对象定义的属性,快速获取指定的子元素
    // tHead, tBodies, tFoot, rows, cells
    var tbody = document.getElementsByTagName('table')[0].tBodies[0];
    //使用array对象的forEach方法遍历数组
    data.forEach(function (value) {
        // console.log(value.name);
        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>

运行实例 »

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


Correction status:qualified

Teacher's comments:
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