使用JS在html中创建具有动态行和列的表

时间:2019-02-07 06:54:08

标签: javascript html css

就我而言,脚本在html页面完全显示之前终止。因此,它无权访问HTML DOM,并且在显示对话框时无法更新元素。这是必需的。

但是我需要根据各种数据创建一个具有动态行和列的表,

<html>
    <body style="overflow:hidden;">

        <?js
        // here the js code must be.
        // I have a json object array, I need to create a table to 
        //display these data. According to the size the table rows and 
         //columns must be changed. 
        ?>

        <!--Body div has autogenerated id.Please do not delete it. --> 
        <div id="bodydiv" class="Blank" style="background-color:rgb(247, 247, 247); height: 100%; width: 100%;">

        <!-- here the html page elements must be created -->
        </div>  

    </body>
</html>

2 个答案:

答案 0 :(得分:0)

这是一个非常常见的问题,因为:

  • javascript附加在html或
  • 之后
  • javascript是在页面加载之前异步加载的。

解决此问题的一种方法是在dom加载后运行javascript:

// your table does not exist here
console.log(document.querySelectorAll('#bodydiv table').length);
window.onload = function whenLoaded() {
   // your table exist here
   console.log(document.querySelectorAll('#bodydiv table').length);
}

即使在下载脚本资源的情况下,大多数情况下也可以正常工作。

如果愿意,只需在<script></script>标记的末尾添加<body />,它也可以使用。

答案 1 :(得分:0)

var jsonArray;    //let's this is your json object array

var table = document.createElement("table");
for(var i=0;i<jsonArray.length;i++){

    var row = table.insertRow(i);

    //insert cells to the row based on the number of element you want to show in table from jsonArray
    var cell0 = row.insertCell(0);
    var cell1 = row.insertCell(1);

    //Assume key1 and key2 are keys in each jsonArray object
    cell1.innerHTML = jsonArray[i].key1; 
    cell2.innerHTML = jsonArray[i].key2;      
}

document.getElementById("divId").appendChild(table);    //consider a div with id 'div1' where you want to show the table

将上述代码放入Javascript函数中,并将此函数保留在<script>标签底部的body标签中。

我认为这是您真正想要的。