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

基于JSON分组渲染HTML列表时.table-wrp区域闭合DIV实现问题求助

解决方案

你遇到的.table-wrp闭合标签缺失问题,是动态拼接分组HTML的常见问题,可通过以下两种方案解决:


方案1:先预处理成分组嵌套结构再生成HTML(推荐,不易出错)

先把原始JSON处理成「分组公共属性+子项列表」的嵌套结构,遍历的时候直接完整生成每个分组的开标签、内容、闭合标签:

// 1. 预处理原始数据生成分组结构
const rawData = [/* 你的原始JSON数据 */];
const groupedResult = rawData.reduce((acc, item) => {
  // 替换为你实际用来分组的公共字段
  const groupKey = item.yourGroupField;
  if (!acc[groupKey]) {
    acc[groupKey] = {
      // 存分组要展示的公共键值对
      commonKV: { yourGroupField: groupKey },
      items: []
    };
  }
  acc[groupKey].items.push(item);
  return acc;
}, {});
const groupList = Object.values(groupedResult);

// 2. 遍历分组生成完整HTML
let htmlStr = '';
groupList.forEach(group => {
  // 开分组容器
  htmlStr += '<div class="table-wrp">';
  // 插入分组头部公共键值对
  htmlStr += '<div class="group-header">';
  Object.entries(group.commonKV).forEach(([key, val]) => {
    htmlStr += `<span>${key}: ${val}</span>`;
  });
  htmlStr += '</div>';
  // 插入当前分组所有子项
  group.items.forEach(item => {
    // 替换为你实际的单条项目渲染逻辑
    htmlStr += `<div class="list-item">${item.itemName}</div>`;
  });
  // 直接闭合当前分组容器,不会漏
  htmlStr += '</div>';
});

// 插入到页面容器
document.querySelector('#yourContainer').innerHTML = htmlStr;

方案2:沿用边遍历边判断分组的写法,补全闭合逻辑

如果你不想调整现有排序遍历逻辑,只要在两处补充闭合逻辑即可:

  1. 检测到分组变更时,先闭合上一个分组的容器
  2. 所有数据遍历结束后,补闭合最后一个分组的容器
const sortedData = [/* 你已经排序完成的原始数据 */];
let htmlStr = '';
let lastGroupKey = null;

sortedData.forEach((item, index) => {
  const currentGroupKey = item.yourGroupField;
  // 检测分组变化
  if (currentGroupKey !== lastGroupKey) {
    // 不是第一个分组的话,先闭合上一个分组
    if (lastGroupKey !== null) {
      htmlStr += '</div>';
    }
    // 新开分组容器、插入头部
    htmlStr += '<div class="table-wrp">';
    htmlStr += `<div class="group-header">分组:${currentGroupKey}</div>`;
  }
  // 渲染当前项
  htmlStr += `<div class="list-item">${item.itemName}</div>`;
  // 更新上一个分组标识
  lastGroupKey = currentGroupKey;
});

// 重点:遍历结束后补闭合最后一个分组的容器
if (sortedData.length > 0) {
  htmlStr += '</div>';
}

document.querySelector('#yourContainer').innerHTML = htmlStr;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 16:15:05