簡體   English   中英

從javascript數組格式填充HTML表

[英]Populate HTML Table from javascript array format

假設我有以下格式的Java腳本數組,

[
"Heading 1",
"Heading 2",
"Data 1",
"Data 2",
"Data 3",
"Data 4",
 ]

我需要以以下格式從數組制作HTML表 在此處輸入圖片說明

我從未從Javascript動態創建HTML表。 誰能幫我嗎?
提前致謝!

在這里,您可以找到一些代碼來完成所需的工作:

 //set the number of columns (we use 2 because you have 2 "Heading") var _numberCol = 2, _arr = [ "Heading 1", "Heading 2", "Data 1", "Data 2", "Data 3", "Data 4" ]; //create a table var $table = document.createElement("table"), $row; for(var _k = 0; _k < _arr.length; _k++){ //we create a row when index is divisible for _numberCol if(_k % _numberCol===0) $row = $table.insertRow(-1); //for each element inside the array we crate a cell inside the current row $col = $row.insertCell(-1); //then we put the value inside like text $col.innerText = _arr[_k]; } //now we can append our table where we need to place it document.body.appendChild($table); 

此代碼僅適用於只有一維的數組類型,並且所有Heading的定義與表中的其他單元格一樣。

如果您在JS中需要它,則可以使用數組為表創建html字符串。 如果然后需要將其放在html頁面的元素中,則可以執行以下操作:

document.getElementById("myDiv").innerHTML = myHtmlTable;

我在此JSfiddle中編寫了一個函數示例來生成這樣的字符串。

(讓我知道您是否無法訪問該提琴,我以前從未將其用於StackOverflow答案)。

 var data = [ "Heading 1", "Heading 2", "Data 1", "Data 2", "Data 3", "Data 4", ] var tabdiv = document.createElement('div'); tabdiv.setAttribute("id", "tab"); document.body.appendChild(tabdiv) document.getElementById("tab").innerHTML = "<table border = '1' style='border-collapse: collapse;'>" +'<tr>' + '<th>'+ data[0] + "</th>" + '<th>'+ data[1] + "</th>" + '</tr>' + '<tr>' + '<td>' + data[2] + '</td>' + '<td>' + data[3] + '</td>' + '</tr>' + '<td>' + data[4] + '</td>' + '<td>' + data[5] + '</td>' + '</tr>'; 

暫無
暫無

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

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