用Javascript动态创建表格 [英] Dynamically creating a table in Javascript
本文介绍了用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);
}
这篇关于用Javascript动态创建表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文