动态创建表格, 执行删除操作

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        table {
            border-collapse: collapse;
        }

        thead {
            background-color: #ccc;
        }

        th,
        td {
            width: 100px;
            height: 40px;
            text-align: center;
        }
    </style>
</head>

<body>
    <h1>动态创建表格</h1>
    <table id="wrap" border="1">
        <thead>
            <tr>
                <th>姓名</th>
                <th>科目</th>
                <th>成绩</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody id="tb">

        </tbody>
    </table>

    <script>
        var tb = document.getElementById("tb");

        var datas = [
            {name:"zs",subject:"语文",score:80},
            {name:"cc",subject:"地理",score:100},
            {name:"op",subject:"生物",score:70},
            {name:"lk",subject:"数学",score:95},
            {name:"io",subject:"历史",score:87},
            {name:"pl",subject:"化学",score:86}
        ]

        for(var i=0; i<datas.length;i++){
            var tr = document.createElement("tr");
            tb.appendChild(tr);

            //每一行内部的 td 
            var data = datas[i];
            //遍历data对象, 根据项数确定添加的td的个数
            for(var k in data){
                var td = document.createElement("td");
                tr.appendChild(td);
                td.innerText = data[k];
            }

            //最后的删除操作
            td = document.createElement("td");
            tr.appendChild(td);

            var a = document.createElement("a");
            a.innerText = "删除";
            a.href = "javascript: void(0);";
            td.appendChild(a);

            //添加删除事件
            a.onclick = function(){
                tb.removeChild(this.parentNode.parentNode);
            }
        }
    </script>

</body>

</html>
posted @ 2021-08-14 18:33  charonmomo  阅读(35)  评论(0编辑  收藏  举报