使用JS动态生成表格

   代码如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script>
        var bgColor;
        var list = [
            { id: '1', country: '中国', capital: '北京',},
            { id: '2', country: '美国', capital: '纽约',},
            { id: '3', country: '英国', capital: '伦敦',},
            { id: '4', country: '日本', capital: '东京',},
            { id: '5', country: '韩国', capital: '首尔',},
            { id: '6', country: '法国', capital: '柏林',}
        ];
        window.onload = function myfunction() {
            var body = window.document.getElementsByTagName("body")[0];
            //创建表格
            var table = window.document.createElement("table");
            table.border = 1;
            body.appendChild(table);

            //创建标题行
            var thead = window.document.createElement("thead");
            var itemHead = list[0];
            for (var index in itemHead) {
                //创建标题单元格添加到thead
                var th = window.document.createElement("th");
                th.innerText = index;
                thead.appendChild(th);
            }
            table.appendChild(thead);

            //遍历对象,创建行和单元格
            for (var i = 0; i < list.length; i++) {
                var item = list[i];
                //创建行
                var tr = window.document.createElement("tr");

                table.appendChild(tr);
                for (var key in item) {
                    //创建单元格
                    var td = window.document.createElement("td");
                    td.innerText = item[key];
                    tr.appendChild(td);
                }
            }
        }
    </script>
</head>
<body>

</body>
</html>

  实现效果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值