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

如何将动态表格的单元格数据提取并追加到UL列表中?

解决表格转嵌套UL列表的问题

问题描述

需要将包含用户姓名及多科目成绩的动态表格,转换为嵌套的无序列表结构:每个用户姓名作为父列表项,其对应的各科成绩作为子列表项。现有jQuery代码未实现嵌套效果,仅生成平级列表。

示例HTML表格

<table id="userScores">
  <thead>
    <tr>
      <th>姓名</th>
      <th>数学</th>
      <th>语文</th>
      <th>英语</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>张三</td>
      <td>90</td>
      <td>85</td>
      <td>92</td>
    </tr>
    <tr>
      <td>李四</td>
      <td>88</td>
      <td>95</td>
      <td>80</td>
    </tr>
  </tbody>
</table>

<!-- 输出容器 -->
<div id="outputContainer">
  <h3>用户成绩列表</h3>
  <ul id="outputList"></ul>
</div>

修正后的jQuery代码

$(document).ready(function() {
  const $outputList = $('#outputList');
  // 提取表头的科目名称(跳过第一个"姓名"列)
  const subjectNames = $('#userScores thead th').slice(1).map(function() {
    return $(this).text();
  }).get();

  // 遍历表格每一行数据
  $('#userScores tbody tr').each(function() {
    const $rowCells = $(this).find('td');
    const userName = $rowCells.eq(0).text();
    
    // 创建父列表项(用户姓名)
    const $parentItem = $('<li>').text(userName);
    // 创建嵌套子列表
    const $childList = $('<ul>');

    // 遍历当前行的成绩单元格(从第二个开始)
    $rowCells.slice(1).each(function(cellIndex) {
      const score = $(this).text();
      const subject = subjectNames[cellIndex];
      $childList.append(`<li>${subject}:${score}</li>`);
    });

    // 组装嵌套结构并添加到输出列表
    $parentItem.append($childList);
    $outputList.append($parentItem);
  });
});

样式优化(可选)

#outputList {
  list-style-type: disc;
  margin: 15px 0;
  padding-left: 20px;
}

#outputList ul {
  list-style-type: circle;
  margin: 5px 0 10px 25px;
  padding-left: 0;
}

#outputList li {
  line-height: 1.5;
}

预期输出效果

  • 张三
    • 数学:90
    • 语文:85
    • 英语:92
  • 李四
    • 数学:88
    • 语文:95
    • 英语:80

核心逻辑说明

  1. 提取科目名称:通过slice(1)跳过表头的"姓名"列,获取所有科目名称,用于后续和成绩对应。
  2. 构建嵌套结构:对每行数据,先创建用户姓名的父列表项,再创建子列表存放该用户的所有成绩。
  3. 关联成绩与科目:遍历每行的成绩单元格时,通过索引对应表头的科目名称,生成清晰的子列表项。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 15:02:49