簡體   English   中英

使用JS在html中創建具有動態行和列的表

[英]Creat table with dynamic rows and columns in a html using JS

就我而言,腳本在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>

這是一個非常常見的問題,因為:

  • 將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);
}

即使在您下載腳本資源的情況下,大多數情況下也可以正常工作。

如果願意,只需在<body />標記的末尾添加<script></script> ,它也可以正常工作。

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函數中,並將此函數保留在body標簽底部的<script>標簽中。

我認為這是您真正想要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM