我如何在这种情况下动态构建 table
how do i build a table dynamically in this scenario
我有一个包含数组数组的变量。它是来自 excel 文件的解析代码。
我想上传我的文件并构建 table,我试过这样:
tabela.forEach((elem, index) => {
console.log(elem[0], index[1])
const row = tableBody.insertRow(index)
const employeeCell = row.insertCell(0)
let content = document.createTextNode(elem[0])
employeeCell.appendChild(content)
})
像这样:
for (let i = 1; i < tabela.length; i++) {
const row = tableBody.insertRow(tabela[1])
const employeeCell = row.insertCell(0)
let content = document.createTextNode(tabela[0])
employeeCell.appendChild(content)
}
但两者都得到了奇怪的结果。
我真的很想了解我在做什么,但遇到了问题。
变量tabela
是13个元素的数组,每个元素是7个元素的数组。
有谁知道我做错了什么如何做到这一点所以我从“tabela”变量的解析代码构建了一个完整的table?
您需要遍历 row
的元素,为每个元素添加一个单元格。
tabela.forEach(elem => {
const row = tableBody.insertRow();
elem.forEach(item => {
const cell = row.insertCell();
cell.innerText = item;
});
})
以下演示展示了如何使用 jQuery
完成任务。
const tablea = [
[30,45,2,9,0],
[455,65,0,5,78],
[1,1,4,4,6]
];
let $tableBody = $('#xdata tbody');
$tableBody.html(
tablea.map(row => $('<tr/>').html(
row.map(cell => $('<td/>').html( cell ))
))
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="xdata"><tbody></tbody></table>
我有一个包含数组数组的变量。它是来自 excel 文件的解析代码。
我想上传我的文件并构建 table,我试过这样:
tabela.forEach((elem, index) => {
console.log(elem[0], index[1])
const row = tableBody.insertRow(index)
const employeeCell = row.insertCell(0)
let content = document.createTextNode(elem[0])
employeeCell.appendChild(content)
})
像这样:
for (let i = 1; i < tabela.length; i++) {
const row = tableBody.insertRow(tabela[1])
const employeeCell = row.insertCell(0)
let content = document.createTextNode(tabela[0])
employeeCell.appendChild(content)
}
但两者都得到了奇怪的结果。
我真的很想了解我在做什么,但遇到了问题。
变量tabela
是13个元素的数组,每个元素是7个元素的数组。
有谁知道我做错了什么如何做到这一点所以我从“tabela”变量的解析代码构建了一个完整的table?
您需要遍历 row
的元素,为每个元素添加一个单元格。
tabela.forEach(elem => {
const row = tableBody.insertRow();
elem.forEach(item => {
const cell = row.insertCell();
cell.innerText = item;
});
})
以下演示展示了如何使用 jQuery
完成任务。
const tablea = [
[30,45,2,9,0],
[455,65,0,5,78],
[1,1,4,4,6]
];
let $tableBody = $('#xdata tbody');
$tableBody.html(
tablea.map(row => $('<tr/>').html(
row.map(cell => $('<td/>').html( cell ))
))
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="xdata"><tbody></tbody></table>