我试图在表格中显示所有数据,但我遇到了一些问题。任何人都可以帮我解决这个问题。在此先感谢..
var obj=[
{
id : "01",
name : "Bob",
prof : "Soft Engg"
},
{
id : "02",
name : "George",
prof : "Admin"
},
{
id : "03",
name : "Paul",
prof : "Front End"
}
];
var x = document.createElement("table");
x.setAttribute("id", "myTable");
document.body.appendChild(x);
var y = document.createElement("tr");
y.setAttribute("id", "myTr");
for(i=0; i<obj.length;i++) {
document.getElementById("myTable").appendChild(y);
var z = document.createElement("td");
var t = document.createTextNode(obj[i]["id"]);
z.appendChild(t);
document.getElementById("myTr").appendChild(z);
}
答案 0 :(得分:2)
好吧,如果你想要对象列表中的所有数据,那么你需要为每个对象添加一行,为该对象的每个属性添加一个单元格(id,name,prof)。现在你只添加一行,然后只添加
这样的东西? https://jsfiddle.net/n3va9cme/
var table = document.createElement("table");
table.setAttribute("id", "myTable");
document.body.appendChild(table);
for(i=0; i<obj.length;i++) {
var row = document.createElement('tr');
table.appendChild(row);
for (key in obj[i]) {
var cell = document.createElement('td');
row.appendChild(cell);
cell.innerHTML = obj[i][key];
}
}
答案 1 :(得分:1)
试试
var obj=[
{
id : "001",
name : "apple",
category : "fruit",
color : "red"
},
{
id : "002",
name : "melon",
category : "fruit",
color : "green"
},
{
id : "003",
name : "banana",
category : "fruit",
color : "yellow"
}
];
var x = document.createElement("table");
x.setAttribute("id", "myTable");
document.body.appendChild(x);
var y = document.createElement("tr");
y.setAttribute("id", "myTr");
for(i=0; i<obj.length;i++) {
document.getElementById("myTable").appendChild(y);
var y = document.createElement("tr");
y.setAttribute("id", "myTr");
var z = document.createElement("td");
var t = document.createTextNode(obj[i]["id"]);
var u = document.createTextNode(obj[i]["name"]);
var n = document.createTextNode(obj[i]["category"]);
var m = document.createTextNode(obj[i]["color"]);
z.appendChild(t);
z.appendChild(u);
z.appendChild(n);
z.appendChild(m);
y.appendChild(z);
document.getElementById("myTr").appendChild(y);
}