我正在尝试使用JavaScript创建表并填充JSON数据,但无法使其正常工作。我想创建五列四行。
到目前为止,我已经创建了标题,但是当我创建populatebody函数并尝试插入名称时,我需要一些填充主体的帮助。名称显示在行中,而不是列中。
var staffs = [
{"name": "James", "gender": "male", "dateofbirth":2011, "joined": "1997", "num_hires": 24000},
{"name": "Anna", "gender": "female", "dateofbirth": 2013, "joined": "1980", "num_hires": 12000},
{"name": "Ken", "gender": "male", "dateofbirth": 2013, "joined": "1980", "num_hires": 13000},
{"name": "Tom", "gender": "male", "dateofbirth": 203, "joined": "1995", "num_hires": 12500}
];
function createheader() {
var table = document.getElementById("header");
var header = table.createTHead(table);
var row = header.insertRow(0);
var head = ["Name", "Gender", "Date of Birth", "join year", " Rentals"];
for (let i = 0; i < head.length; i++) {
let cell = document.createElement("td");
cell.innerText = head[i];
row.append(cell);
}
}
function populatebody() {
var table = document.getElementById("details");
var tbody = table.createTBody(table);
var row = tbody.insertRow(0);
for (var i = 0; i < staffs.length; i++) {
let cell = document.createElement("td");
cell.innerHTML = staffs[i].name;
row.append(cell);
}
}
答案 0 :(得分:1)
在循环中创建一行,生成原始HTML单元格(td
元素)并更新原始元素的内容(tr
)。
var staffs = [
{"name": "James", "gender": "male", "dateofbirth":2011, "joined": "1997", "num_hires": 24000},
{"name": "Anna", "gender": "female", "dateofbirth": 2013, "joined": "1980", "num_hires": 12000},
{"name": "Ken", "gender": "male", "dateofbirth": 2013, "joined": "1980", "num_hires": 13000},
{"name": "Tom", "gender": "male", "dateofbirth": 203, "joined": "1995", "num_hires": 12500}
];
function createheader() {
var table = document.getElementById("table");
var header = table.createTHead(table);
var row = header.insertRow(0);
var head = ["Name", "Gender", "Date of Birth", "join year", " Rentals"];
for (let i = 0; i < head.length; i++) {
let cell = document.createElement("td");
cell.innerText = head[i];
row.append(cell);
}
}
function populatebody() {
var table = document.getElementById("table");
var tbody = table.createTBody(table);
for (var i = 0; i < staffs.length; i++) {
var row = tbody.insertRow(0);
row.innerHTML = `
<td>${staffs[i].name}</td>
<td>${staffs[i].gender}</td>
<td>${staffs[i].dateofbirth}</td>
<td>${staffs[i].joined}</td>
<td>${staffs[i].num_hires}</td>
`;
}
}
createheader();
populatebody();
<table id="table"></table>