jQuery创建表格

412 阅读1分钟

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery创建表格</title>
    <style>
        table {
            border-spacing: 0;
            width: 450px;
        }

        td {
            border-bottom: 1px solid skyblue;
            text-align: center;
            height: 50px;
        }

        .btn {
            width: 55px;
            height: 25px;
            background-color: rgb(241, 70, 70);
            border-radius: 10px;
            border: none;
            color: #fff;
            outline: none;
            transition: all .5s ease;
            cursor: pointer;
        }

        .btn:hover {
            background-color: rgb(212, 110, 110);
        }
    </style>
</head>

<body>
    <div class="main">

    </div>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <script>
        $(function () {
            let arr = [{
                id: 1,
                name: "Tom",
                age: 10
            }, {
                id: 2,
                name: "Mary",
                age: 20
            }, {
                id: 3,
                name: "Lili",
                age: 30
            }, {
                id: 4,
                name: "Cat",
                age: 40
            }, {
                id: 5,
                name: "Dog",
                age: 50
            }, {
                id: 6,
                name: "Fish",
                age: 60
            }, {
                id: 7,
                name: "Dog",
                age: 70
            }];
            let table = $("<table/>");
            let th1 = $("<th/>").html("编号");
            let th2 = $("<th/>").html("姓名");
            let th3 = $("<th/>").html("年龄");
            let th4 = $("<th/>").html("操作");
            let thead = $("<tr/>").append(th1).append(th2).append(th3).append(th4);
            table.append(thead);
            arr.forEach(item => {
                let tr = $("<tr/>");
                Object.values(item).forEach(v => {
                    let td = $("<td/>").html(v);
                    tr.append(td);
                });
                let btn = $("<button/>").addClass("btn del").html("删除");
                let td = $("<td/>").html(btn);
                tr.append(td);
                table.append(tr);
            });
            $(".main").append(table);
            $(".del").click(function () {
                if (confirm("您确定删除吗?")) {
                    $(this).parents("tr").remove()
                }
            });
        });
    </script>
</body>

</html>