繁体   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