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

如何通过HTML Template将JSON中Accessories数据填充到表格行?

实现嵌套accessories数据生成表格行的方案

核心思路:定位表格的<tbody>元素,遍历accessories数组,为每个数据项生成独立的<tr>元素并插入到tbody中。下面提供几种常用实现方式:

方式1:直接创建DOM元素(安全推荐)

适合大多数场景,可避免XSS风险:

HTML模板

<table id="accessoriesTable">
  <thead>
    <tr>
      <th>名称</th>
      <th>价格</th>
      <th>库存</th>
    </tr>
  </thead>
  <!-- 给tbody设置id方便定位 -->
  <tbody id="accessoriesBody"></tbody>
</table>

JavaScript代码

// 假设你的JSON数据结构如下(根据实际结构调整)
// {
//   "mainProduct": {
//     "name": "XX产品",
//     "accessories": [
//       {"name": "配件A", "price": 9.9, "stock": 100},
//       {"name": "配件B", "price": 19.9, "stock": 50}
//     ]
//   }
// }

fetch('你的JSON数据接口地址')
  .then(res => res.json())
  .then(data => {
    // 取出嵌套的accessories数组,路径根据你的JSON结构修改
    const accessoriesList = data.mainProduct.accessories;
    const tbody = document.getElementById('accessoriesBody');
    
    // 先清空tbody原有内容(可选,防止重复加载)
    tbody.innerHTML = '';
    
    // 遍历每个配件项
    accessoriesList.forEach(item => {
      // 创建<tr>元素
      const row = document.createElement('tr');
      
      // 创建并填充每个<td>
      const nameCell = document.createElement('td');
      nameCell.textContent = item.name;
      
      const priceCell = document.createElement('td');
      priceCell.textContent = `¥${item.price.toFixed(2)}`;
      
      const stockCell = document.createElement('td');
      stockCell.textContent = item.stock;
      
      // 将<td>添加到<tr>
      row.appendChild(nameCell);
      row.appendChild(priceCell);
      row.appendChild(stockCell);
      
      // 将<tr>添加到tbody
      tbody.appendChild(row);
    });
  })
  .catch(err => console.error('数据加载失败:', err));

方式2:使用HTML模板标签(适合复杂行结构)

如果表格行结构复杂,用<template>标签复用结构更清晰:

HTML模板

<!-- 定义行模板 -->
<template id="accessoryRowTpl">
  <tr>
    <td class="accessory-name"></td>
    <td class="accessory-price"></td>
    <td class="accessory-stock"></td>
  </tr>
</template>

<table id="accessoriesTable">
  <thead>
    <tr>
      <th>名称</th>
      <th>价格</th>
      <th>库存</th>
    </tr>
  </thead>
  <tbody id="accessoriesBody"></tbody>
</table>

JavaScript代码

fetch('你的JSON数据接口地址')
  .then(res => res.json())
  .then(data => {
    const accessoriesList = data.mainProduct.accessories;
    const tbody = document.getElementById('accessoriesBody');
    const rowTemplate = document.getElementById('accessoryRowTpl');
    
    tbody.innerHTML = '';
    
    accessoriesList.forEach(item => {
      // 克隆模板内容
      const rowFragment = rowTemplate.content.cloneNode(true);
      
      // 填充模板中的内容
      rowFragment.querySelector('.accessory-name').textContent = item.name;
      rowFragment.querySelector('.accessory-price').textContent = `¥${item.price.toFixed(2)}`;
      rowFragment.querySelector('.accessory-stock').textContent = item.stock;
      
      // 将克隆的行插入tbody
      tbody.appendChild(rowFragment);
    });
  })
  .catch(err => console.error('数据加载失败:', err));

方式3:innerHTML拼接(简单场景快速实现)

适合结构简单、数据可信的场景,代码更简洁:

JavaScript代码

fetch('你的JSON数据接口地址')
  .then(res => res.json())
  .then(data => {
    const accessoriesList = data.mainProduct.accessories;
    const tbody = document.getElementById('accessoriesBody');
    
    // 拼接所有行的HTML字符串
    let rowsHtml = '';
    accessoriesList.forEach(item => {
      rowsHtml += `
        <tr>
          <td>${item.name}</td>
          <td>¥${item.price.toFixed(2)}</td>
          <td>${item.stock}</td>
        </tr>
      `;
    });
    
    // 一次性插入到tbody
    tbody.innerHTML = rowsHtml;
  })
  .catch(err => console.error('数据加载失败:', err));

关键注意点

  • 确保tbody的id正确,能通过document.getElementById准确定位到。
  • 根据你的实际JSON结构调整accessories数组的获取路径(比如如果是根节点的数组,就用data.accessories)。
  • 如果数据包含用户输入内容,优先用方式1或2,避免innerHTML拼接带来的XSS风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 09:06:38