JS 动态生成Table的三种方法

<!DOCTYPE HTML>
<html>

<head>
    <title>JSON字符串转换为JSON对象数组 </title>
</head>

<body style="text-align:center;">
    <h1 style="color:#1ab1cc;"> 公众号:web前端开发 </h1>
    <p id="GFG_UP"></p> <button onclick="display()"> Click Here </button>
    <p id="GFG_DOWN"></p>
    <table id="table01" border="1" cellspacing="0" align="center">
        <tr style="height: 30px;"> 
            <td style="width: 100px;">Data</td>
            <td style="width: 100px;background-color: aqua;">Data2</td>
        </tr>
        <tbody id="table01Tbody"></tbody>
    </table>
    <script>         
        var up = document.getElementById("GFG_UP"); 
        var JS_Obj = '[{"prop_1":"val_1"}, {"prop_1":"val_2"}, {"prop_1" : "val_3"}]';
        up.innerHTML = "JSON string - '" + JS_Obj + "'";
        var down = document.getElementById("GFG_DOWN");
        var obj = JSON.parse(JS_Obj); 
        function myGFG() {
            var res = [];
            for (var i in obj) 
                res.push(obj[i].prop_1);
            down.innerHTML = "Array of values - [" + res + "]";
        }
        var tab = document.getElementById("table01");
        var str = '';
        function display(){
            myGFG();
            for (var i in obj){
                /* 方法一
                var td_id = document.createElement("td");
                var text_id = document.createTextNode(obj[i].prop_1); 
                td_id.appendChild(text_id);
                var tr = document.createElement("tr");
                tr.appendChild(td_id);
                tab.appendChild(tr);
                */
                /* 方法二
                var tr=tab.insertRow(1);
                var cell0=tr.insertCell(0);
                cell0.innerHTML=i;
                var cell1=tr.insertCell(1);
                cell1.innerHTML=obj[i].prop_1;
                */
                // 方法三,推荐
                str += `
                    
                        ${i}
                        ${obj[i].prop_1}
                    
                `;
            }
            //var tbody = document.querySelector('tbody');
            var tbody = document.getElementById('table01Tbody');
            tbody.innerHTML = str;
        }
    </script>
</body>

</html>

你可能感兴趣的:(javascript,前端,json)