JavaScript动态创建表格

2021/12/9 1:16:56

本文主要是介绍JavaScript动态创建表格,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>动态创建表格练习</title>
        <!-- <script src="js包/common.js"></script> -->
    </head>
    <body>
        <div id="box">

        </div>
    </body>
</html>
<script>
    var data=[
        {name:"傅红雪",subject:"数学",score:"89"},
        {name:"叶开",subject:"语文",score:"55"},
        {name:"公子羽",subject:"政治",score:"44"},
        {name:"花无缺",subject:"美术",score:"23"},
    ],

    theadData=["姓名","科目","成绩","操作"];

    var div=document.getElementById("box");
    var table=document.createElement("table");

    table.width="200px";
    table.height="200px";
    table.border="1px";
    table.style.borderCollapse="collapse";
    div.appendChild(table);

    var thead=document.createElement("thead");
    table.appendChild(thead);

    var tr=document.createElement("tr");
    thead.appendChild(tr);

    for (var i = 0; i < theadData.length; i++) {

        var th=document.createElement("th");
        tr.appendChild(th);

        // setInnerText(th,theadData[i]);
        th.innerText=theadData[i];
    }


    //创建其他行
    var tbody=document.createElement("tbody");
    table.appendChild(tbody);

    for (var i = 0; i < data.length; i++) {

        datas=data[i];
        var tr=document.createElement("tr");
        tbody.appendChild(tr);
       

        for (var key in datas) {

            var td=document.createElement("td");
            tr.appendChild(td);

            // setInnerText(td,datas[key]);
            td.innerText=datas[key];
        }

        //删除行
        // var tr=document.createElement("tr");
        // tbody.appendChild(tr);

        var td=document.createElement("td");
        tr.appendChild(td);

        var a=document.createElement("a");
        a.href="#";
        td.appendChild(a);

        // setInnerText(a,"删除");
        a.innerText="删除";
        a.onclick=link;
        
    }

    function link() {
        tr=this.parentNode.parentNode;
        tbody.removeChild(tr);
    }

</script>

效果图
效果图



这篇关于JavaScript动态创建表格的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程