Laravel实现:将数组首行设为表头其余作为表体数据
动态生成表格表头与表体的实现方法
假设你的数组格式如下(对应图片中的结构):
const tableData = [ ["订单编号", "订单状态", "下单时间", "操作"], ["NO.12345", "已完成", "2024-05-20", "查看详情"], ["NO.12346", "待发货", "2024-05-21", "查看详情"], // 更多数据行... ];
基于你提供的表格结构,用原生JavaScript实现动态渲染的代码如下:
<table class="table hover"> <thead> <tr> </tr> </thead> <tbody> </tbody> </table> <script> // 数据源示例 const tableData = [ ["订单编号", "订单状态", "下单时间", "操作"], ["NO.12345", "已完成", "2024-05-20", "查看详情"], ["NO.12346", "待发货", "2024-05-21", "查看详情"], ]; // 获取表格的表头行和表体容器 const theadTr = document.querySelector('table thead tr'); const tbody = document.querySelector('table tbody'); // 生成表头 const headers = tableData[0]; headers.forEach(headerText => { const th = document.createElement('th'); th.textContent = headerText; theadTr.appendChild(th); }); // 生成表体数据 const bodyRows = tableData.slice(1); bodyRows.forEach(rowData => { const tr = document.createElement('tr'); rowData.forEach(cellText => { const td = document.createElement('td'); td.textContent = cellText; tr.appendChild(td); }); tbody.appendChild(tr); }); </script>
实现逻辑说明:
- 数据源第一行作为表头字段,后续行作为表格内容行
- 通过DOM选择器定位表格的表头行和表体容器
- 遍历数组第一行,逐个创建
<th>元素并插入到表头行 - 从数组第二行开始遍历,每一行创建一个
<tr>,再遍历该行数据创建<td>,最后将整行插入到表体中
内容的提问来源于stack exchange,提问作者Hola
相关产品推荐
相关产品推荐

