JS-生成表格和颜色-JSON对象用forin循环

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script>

        var list = [
            { id: '1', country: '中国', captical: '北京' },
            { id: '2', country: '日本', captical: '东京' },
            { id: '3', country: '美国', captical: '华盛顿' },
            { id: '4', country: '英国', captical:'伦敦'}
        ];

        onload = function () {
            var body = this.document.getElementsByTagName('body')[0];
            var table = this.document.createElement('table');
            table.border = '1';
            body.appendChild(table);

            var thead = this.document.createElement('thead');
            for (var key in list[0]) {
                var th = this.document.createElement('th');
                th.innerHTML = key;
                thead.appendChild(th);
            }

            table.appendChild(thead);

            for (var i = 0; i < list.length; i++) {
                var tr = document.createElement('tr');

               //指向时候高亮,离开时候恢复到原来的背景色

                var oldColor;
                tr.onmouseover = function () {
                    oldColor = this.style.backgroundColor;
                    this.style.backgroundColor = 'yellow';
                }
                tr.onmouseleave = function () {
                    this.style.backgroundColor = oldColor;
                }

                table.appendChild(tr);
                if (i % 2 == 0) {
                    tr.style.backgroundColor = 'green';
                } else {
                    tr.style.backgroundColor = 'yellow';
                }
                for (var index in list[i]) {
                    var td = document.createElement('td');
                    td.innerHTML = list[i][index];
                    tr.appendChild(td);
                }

                
            }
            
        }
    </script>
</head>
<body>

</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值