Dynamically creating a table in Javascript

一曲冷凌霜 提交于 2019-12-12 01:57:41

问题


I have got a working table that when the button is pushed, a table is dynamically created by looping through an array and displaying that data in each cell.

However the problem arises when I am trying to add a table header for my table, and I'm not sure what I am doing wrong.

Here is my current working code: (although doesn't seem to work in JSFiddle?!)

And here is the code I am trying to add: (which must be wrong)

var thd=document.createElement("thead");
tab.appendChild(thd);

var tr= document.createElement("tr"); 
tbdy.appendChild(tr); 

var th= document.createElement("th");
th.appendChild(document.createTextNode("Name");
tr.appendChild(th);

Any help would be greatly appreciated,


回答1:


You can use a loop to avoid duplicating code. For example:

var columns = ["Name", "Age", "Degree"];

var thd = document.createElement("thead");
tab.appendChild(thd);

var tr = document.createElement("tr"); 
thd.appendChild(tr);

for (var i = 0; i < columns.length; i++) {
    var th = document.createElement("th");
    th.appendChild(document.createTextNode(columns[i]));
    tr.appendChild(th);    
}

Demo: http://jsfiddle.net/ahEkH/6/



来源:https://stackoverflow.com/questions/23974710/dynamically-creating-a-table-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!