在Javascript中动态创建表

问题描述 投票:0回答:1

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

但是,当我尝试为我的表添加表头时出现问题,我不确定我做错了什么。

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

以下是我要添加的代码:(一定是错的)

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

任何帮助将不胜感激,

javascript html-table appendchild createelement
1个回答
0
投票

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

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/

© www.soinside.com 2019 - 2024. All rights reserved.