javascript - jquery从数组动态创建表
问题描述
我目前正在尝试从数组创建一个表。数组的格式如下:
[
{
header: 'ID',
values: [1, 2]
},
{
header: 'First Name',
values: ['John', 'Jayne']
},
{
header: 'Last Name',
value: ['Doe', 'Doe']
}
]
我已经成功地为表格创建了标题,但是对于从这个数组中以这种方式在哪里或如何处理正文中的渲染有点困难。
const exampleArray = [
{
header: 'ID',
values: [1, 2]
},
{
header: 'First Name',
values: ['John', 'Jayne']
},
{
header: 'Last Name',
values: ['Doe', 'Doe']
}
];
const header = $('#results thead tr');
const body = $('#results tbody');
exampleArray.forEach((row) => {
header.append(
$(`<th>${row.header}</th>`)
);
});
<table id="results">
<thead>
<tr>
<!-- HEADERS -->
</tr>
</thead>
<tbody>
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
我不确定这是否是最好的方法,或者在尝试渲染表格之前是否值得将结果集映射到更可变的东西。
解决方案
您调用行中的元素exampleArray
,而它们实际上是列。这可能是产生混乱的地方。有关工作示例,请参见下面的代码段。
const exampleArray = [
{
header: 'ID',
values: [1, 2]
},
{
header: 'First Name',
values: ['John', 'Jayne']
},
{
header: 'Last Name',
values: ['Doe', 'Doe']
}
];
const header = $('#results thead tr');
const body = $('#results tbody');
exampleArray.forEach((column) => {
header.append(
$(`<th>${column.header}</th>`)
);
});
// Compute the number of rows in the array
const nRows = exampleArray[0].values.length;
for (let i = 0; i < nRows; i++) {
// row contains all cells in a row
let row = $("<tr/>");
// Loop over the columns
exampleArray.forEach((column) => {
// For each column, we add the i-th value, since we're building the i-th row
row.append(`<td>${column.values[i]}</td>`);
});
// Add the row to the table body
body.append(row);
}
<table id="results">
<thead>
<tr>
<!-- HEADERS -->
</tr>
</thead>
<tbody>
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
推荐阅读
- mongodb - Mongodb 一次往返执行多个查询
- c# - C# 与 C++ 静态数组中静态常量列表初始化的效率
- spring-data-redis - Spring Data Redis 的自定义 @Id 类
- angularjs - Firebase 部署显示没有应用内容的欢迎屏幕 Firebase 部署显示
- javascript - 为什么我需要调用函数而不是方法?
- dataset - 具有空白节点的 SPARQL 多数据集
- ruby-on-rails - 在 Ruby 中搜索嵌套数组的更好方法?
- python - 如何在 Keras 中实现随机池化
- javascript - React 子组件传递了一个函数,但在运行时未显示函数。
- git - 自动化部署任务(用例)