Blogger Information
Blog 29
fans 0
comment 0
visits 25404
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
使用JS动态一张表格,数据用数组进行模拟2019年1月17日作业
连界现代周伟的博客
Original
649 people have browsed it

实例(用JS动态生成一张成绩表)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JS操作表格的基本技巧</title>
    <style>
      table, td, th {
          border: 1px solid #666;
      }
    
    table {
        width: 500px;
        border-collapse: collapse;
        text-align: center;
    }

    table caption {
        font-size: 1.2rem;
        margin-bottom: 15px;
    }

    thead tr:nth-of-type(1) {
        background-color: lightcyan;
    }
    </style>
</head>
<body>
    <table id="cart1">
        <caption>成绩表</caption>
        <thead>
           <tr>
               <td>编号</td>
               <td>姓名</td>
               <td>科目</td>
               <td>成绩</td>
           </tr>
        </thead>
        
        <tbody></tbody>
    </table>

    <script>
    // var cart1 = document.getElementById('cart1');
    // console.log(cart1.children[2].children[1].children[1].innerText);
    // console.log(cart1.children[2].children[1].children[3].innerText);
    // cart1.children[2].children[1].children[3].innerText = 86;
    // 用Js对象的方式来提供数据,动态生成一个表格

    // 对象数组
    var data = [
        {id: 1, name: '小李', subject: '数学', score: '95'},
        {id: 2, name: '小王', subject: '数学', score: '80'},
        {id: 3, name: '小张', subject: '数学', score: '86'}
    ];

    var cart1 = document.getElementById('cart1');
    var tbody = cart1.children[2]; //返回tbody
    //遍历对象数组   value是一个对象
    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.subject + '</td>';
        tr.innerHTML += '<td>' + value.score + '</td>';
        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