简体   繁体   English

从javascript数组格式填充HTML表

[英]Populate HTML Table from javascript array format

Suppose i have an java script Array in the following format, 假设我有以下格式的Java脚本数组,

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

I need to make a HTML table from the array in the following format 我需要以以下格式从数组制作HTML表 在此处输入图片说明

I've never dynamically created an HTML Table from Javascript. 我从未从Javascript动态创建HTML表。 Can anyone help me out? 谁能帮我吗?
Thanks in advance! 提前致谢!

Here you can find some code to make what you need to: 在这里,您可以找到一些代码来完成所需的工作:

 //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); 

This code works only with your type of array that has only one dimension, and all Heading are defined like each other cell in the table. 此代码仅适用于只有一维的数组类型,并且所有Heading的定义与表中的其他单元格一样。

If you need it in JS you can use the array to create an html string for the table. 如果您在JS中需要它,则可以使用数组为表创建html字符串。 If you then need to put it inside an element in your html page you could do something like: 如果然后需要将其放在html页面的元素中,则可以执行以下操作:

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

I wrote an example of a function to generate such a string in this JSfiddle . 我在此JSfiddle中编写了一个函数示例来生成这样的字符串。

(Let me know if you can't access the fiddle, I've never used it before for StackOverflow answers). (让我知道您是否无法访问该提琴,我以前从未将其用于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