用Javascript动态创建表格

问题描述:

我有一个工作表,当按下按钮时,通过循环遍历数组并在每个单元格中显示该数据来动态创建表.

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.

这是我当前的工作代码:(尽管在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);

任何帮助将不胜感激,

您可以使用循环来避免重复代码.例如:

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