首页 > 解决方案 > 使用 JS 在 html 中创建具有动态行和列的表

问题描述

在我的情况下,脚本在完全显示 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>

标签: javascripthtmlcss

解决方案


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

  • 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 />


推荐阅读