动态生成表格案例
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        table{
            margin: 100px auto;
            border: 1px solid black;
        }
        thead tr{
            background-color: grey;
        }
        thead tr th{
            border: 1px solid black;
        }
        tbody tr{
            text-align: center;
            background-color: rgb(109, 201, 185);
        }
        tbody tr td{
            border: 1px solid black;
        }
    </style>
</head>
<body>
    <table>
        <thead>
            <tr>
                <th>name</th>
                <th>subject</th>
                <th>score</th>
                <th>action</th>
            </tr>
        </thead>
        <tbody>

        </tbody>
    </table>
    <script>
        var datas = [
            {
                name:'john',
                subject:'math',
                score:'99'
            },
            {
                name:'king',
                subject:'english',
                score:'75'
            },
            {
                name:'micheal',
                subject:'chinese',
                score:'100'
            }
        ]
        var tbody = document.querySelector('tbody')
       
        for (var index = 0; index < datas.length; index++) {
            var tr = document.createElement('tr')
            tbody.appendChild(tr)
            for (var k in datas[index]) {
                var td = document.createElement('td')
                // console.log(datas[index]);
                // console.log(datas[index][k]);
                td.innerHTML = datas[index][k]
                tr.appendChild(td)

            }
            var td = document.createElement('td')
            td.innerHTML = '<a href="javascript:;">detele</a>'
            td.style.cssText='background-color:rgb(201, 176, 109);'
            tr.appendChild(td)
            
        }
        var as = document.querySelectorAll('a')
        for (let index = 0; index < as.length; index++) {
            as[index].onclick = function(){
               tbody.removeChild(this.parentNode.parentNode)
            } 
        }
    </script>
</body>

</html>
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐