You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript for循环动态填充HTML表格数据

解决方案

核心调整逻辑如下:

  1. 移除原HTML中预留的单行空数据节点,新增<tbody>标签作为动态内容的容器,解决id重复无法适配多行数据的问题
  2. 封装通用渲染函数,后续从后端接口拿到数据后直接调用函数传入数据即可完成刷新,不用重复编写逻辑
  3. 遍历数据时动态创建行、单元格节点,完成数据赋值后插入表格

完整可运行代码如下:

<table id="table">
  <tr>
    <th>Item</th>
    <th>Quantity</th>
    <th>Total</th>
  </tr>
  <tbody id="tableBody"></tbody>
</table>

<script>
// 模拟后端返回的数据
const items = [
  {item: "Americano", quantity: 1, total: "12.52 sar"  },
  {item: "Frape", quantity: 3, total: "13.40 sar"  },
  {item: "Espresso", quantity: 2, total: "10.12 sar"  },
];

// 表格渲染函数,参数为后端返回的数组数据
function renderTable(data) {
  const tableBody = document.getElementById('tableBody');
  // 清空原有内容,避免重复渲染
  tableBody.innerHTML = '';
  // 遍历每条数据生成对应行
  data.forEach(goods => {
    const tr = document.createElement('tr');
    // 商品名称单元格
    const itemTd = document.createElement('td');
    itemTd.textContent = goods.item;
    // 数量单元格
    const quantityTd = document.createElement('td');
    quantityTd.textContent = goods.quantity;
    // 总价单元格
    const totalTd = document.createElement('td');
    totalTd.textContent = goods.total;
    // 组装行节点
    tr.append(itemTd, quantityTd, totalTd);
    tableBody.appendChild(tr);
  })
}

// 首次加载渲染数据
renderTable(items);

// 后续对接后端接口示例(伪代码)
// fetch('/api/getGoodsList')
//   .then(res => res.json())
//   .then(data => renderTable(data))
</script>

内容的提问来源于stack exchange,提问作者simpledev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 17:54:02