我正在使用 JavaScript DOM 创建一个表,我需要将数组 (thValues) 中的所有值插入到 TR(表行)中包含的每个 TH 中。我怎样才能做到呢?
let thValues = ["Text 1", "Text 2", "Text 3", "Text 4", "Text 5", "Text 6"];
let pickTableZone = document.getElementById("tableDetails");
let table = document.createElement("table");
pickTableZone.appendChild(table);
table.setAttribute("class", "table table-responsive-sm table-striped");
let tableBody = document.createElement("tbody");
table.appendChild(tableBody); //adding tbody to table
//for the length of thValues create table rows
for (let i = 0; i < thValues.length; i++) {
let tableRow = document.createElement("tr");
tableBody.appendChild(tableRow); //adding TR to TBODY
let tableHead = document.createElement("th");
tableRow.appendChild(tableHead); //adding TH to TR
tableHead.setAttribute("scope", "row"); //adding attributes to TH
let text = document.createTextNode(thValues[0]); //Assign each text from the thValues in each TH from the TR's
tableHead.appendChild(text); //adding text to TH
let tableData = document.createElement("td");
tableRow.appendChild(tableData); //adding TD to TR
let textInTD = document.createTextNode("Time 1");
tableData.appendChild(textInTD); //adding text to TD
}
table, th, td {
border: 1px solid gray;
border-collapse: collapse;
padding: 1rem;
}
<div id="tableDetails">
最佳答案
您需要两个循环:一个循环用第 th
个单元格填充头行;一个用于创建带有 td
单元格的正文行。按照目前的情况,您将为每个 header 值创建一个新行,而不是将它们全部放在一行中。您还将头部细胞放入 tbody
而不是 thead
中。
以下是创建标题行的方法。
const thValues = ["Text 1", "Text 2", "Text 3", "Text 4", "Text 5", "Text 6"];
const pickTableZone = document.getElementById("tableDetails");
const table = document.createElement("table");
pickTableZone.appendChild(table);
table.setAttribute("class", "table table-responsive-sm table-striped");
const tableHead = document.createElement("thead");
table.appendChild(tableHead); //adding thead to table
const headRow = document.createElement("tr");
tableHead.appendChild(headRow); // Row for the head cells.
// Add each header.
for (let i = 0; i < thValues.length; ++i) {
const headCell = document.createElement("th");
headRow.appendChild(headCell); //adding head cell to head row
const text = document.createTextNode(thValues[i]);
headCell.appendChild(text); //adding text to TH
}
const tableBody = document.createElement("tbody");
table.appendChild(tableBody); //adding tbody to table
// for each row of data
// add a tr to tbody
// for each column (e.g. thValues.length)
// add a td to the tr
table, th, td {
border: 1px solid gray;
border-collapse: collapse;
padding: 1rem;
}
<div id="tableDetails"></div>
从您的帖子中并不清楚您想要在 tbody
中放入什么内容,因为您只是一遍又一遍地重复“Time 1”。因此,我留下了一些伪代码来填充主体。
顺便说一句,除非您打算重新分配变量 ( for a number of reasons ),否则您应该使用 const
而不是 let
。
关于javascript - 使用数组中的值填充表行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59565741/