首页 > web前端 > js教程 > 正文

JavaScript中按ID分组数据并动态生成带有全选功能的学生列表

心靈之曲
发布: 2025-08-31 23:22:01
原创
528人浏览过

JavaScript中按ID分组数据并动态生成带有全选功能的学生列表

本教程详细介绍了如何使用JavaScript对复杂列表数据进行分组,并根据分组结果动态生成带有“全选”功能的HTML用户界面。通过Array.prototype.reduce实现数据高效分组,利用Object.values和Array.prototype.map构建动态HTML结构,最后通过事件监听器为每个分组实现“全选”复选框的交互逻辑。

1. 数据结构与需求分析

前端开发中,我们经常需要处理从后端获取的列表数据。假设我们有一个包含学生信息的数组,每个学生记录都包含学校、家长和学生本人的详细信息,其中student.id用于标识学生的唯一id。

原始数据示例:

const res = {
  List: [
    { "School information": { RegId: 1, Name: "SJ" }, ParentInfo: { Id: 0, Name: "Abc" }, Student: { Id: 1, Name: "Student1" } },
    { "School information": { RegId: 1, Name: "" }, ParentInfo: { Id: 0, Name: "" }, Student: { Id: 5, Name: "Student6" } },
    { "School information": { RegId: 1, Name: "" }, ParentInfo: { Id: 0, Name: "" }, Student: { Id: 1, Name: "Student3" } },
    { "School information": { RegId: 1, Name: "" }, ParentInfo: { Id: 0, Name: "" }, Student: { Id: 5, Name: "Student5" } },
    { "School information": { RegId: 1, Name: "" }, ParentInfo: { Id: 0, Name: "" }, Student: { Id: 1, Name: "Student4" } },
    { "School information": { RegId: 1, Name: "" }, ParentInfo: { Id: 0, Name: "" }, Student: { Id: 7, Name: "Student9" } },
    { "School information": { RegId: 1, Name: "" }, ParentInfo: { Id: 0, Name: "" }, Student: { Id: 7, Name: "Student11" } }
  ]
};
登录后复制

目标需求:

我们需要将这些学生记录按照Student.Id进行分组,并在每个分组的顶部添加一个“Select All Students”的复选框。点击该复选框时,同组内的所有学生复选框应同步选中或取消选中。

期望的HTML输出结构:

立即学习Java免费学习笔记(深入)”;

<!-- 针对Student.Id为1的分组 -->
<div>
  <label>Select All Studentds <input type="checkbox" class="group"></label><br>
  <label><input type="checkbox">Student1</label><br>
  <label><input type="checkbox">Student3</label><br>
  <label><input type="checkbox">Student4</label>
</div>

<!-- 针对Student.Id为5的分组 -->
<div>
  <label>Select All Studentds <input type="checkbox" class="group"></label><br>
  <label><input type="checkbox">Student6</label><br>
  <label><input type="checkbox">Student5</label>
</div>

<!-- 针对Student.Id为7的分组 -->
<div>
  <label>Select All Studentds <input type="checkbox" class="group"></label><br>
  <label><input type="checkbox">Student9</label><br>
  <label><input type="checkbox">Student11</label>
</div>
登录后复制

2. 数据分组处理

实现此需求的第一步是将原始的扁平化列表数据根据Student.Id进行分组。Array.prototype.reduce方法是实现这一目标的强大工具

const result = res.List.reduce((accumulator, currentItem) => {
    // 使用学生ID作为键,将学生姓名添加到对应的数组中
    // 如果该ID的数组不存在,则使用空数组进行初始化 (??= 是ES2021的空值合并赋值运算符)
    (accumulator[currentItem.Student.Id] ??= []).push(currentItem.Student.Name);
    return accumulator;
}, {}); // 初始累加器为一个空对象
登录后复制

代码解析:

序列猴子开放平台
序列猴子开放平台

具有长序列、多模态、单模型、大数据等特点的超大规模语言模型

序列猴子开放平台 0
查看详情 序列猴子开放平台
  • reduce((accumulator, currentItem) => { ... }, {}): reduce方法遍历res.List中的每个元素。accumulator是累积结果(一个对象),currentItem是当前正在处理的列表项。初始accumulator是一个空对象{}。
  • accumulator[currentItem.Student.Id]: 尝试访问accumulator中以当前学生ID为键的属性。
  • ??= []: 这是ES2021引入的空值合并赋值运算符。如果accumulator[currentItem.Student.Id]的值为null或undefined,则将其赋值为[](一个空数组)。否则,保持其原有值。这确保了每个学生ID第一次出现时,都会创建一个新的空数组。
  • .push(currentItem.Student.Name): 将当前学生的姓名添加到对应ID的数组中。

经过此步骤,result对象将是以下结构:

{
  "1": ["Student1", "Student3", "Student4"],
  "5": ["Student6", "Student5"],
  "7": ["Student9", "Student11"]
}
登录后复制

3. 动态生成用户界面

有了分组后的数据,接下来就是将其转换为HTML结构并呈现在页面上。我们可以使用Object.values获取分组后的数组,然后再次利用Array.prototype.map来生成每个分组的HTML。

document.getElementById("container").innerHTML =
  Object.values(result) // 获取所有学生ID对应的学生姓名数组
    .map(group =>
      // 为每个分组创建一个div
      '<div>' +
      // 添加“Select All Students”复选框
      '<label>Select All Studentds <input type="checkbox" class="group"></label><br>' +
      // 遍历组内学生,为每个学生创建复选框
      group.map(studentName => `<label><input type="checkbox">${studentName}</label>`).join("<br>") +
      '</div>'
    )
    .join(""); // 将所有分组的HTML字符串连接起来
登录后复制

代码解析:

  • Object.values(result): 这会返回一个数组,其中包含result对象的所有值。在本例中,它将是[["Student1", "Student3", "Student4"], ["Student6", "Student5"], ["Student9", "Student11"]]。
  • .map(group => { ... }): 再次使用map方法,这次是遍历每个学生姓名数组(即每个分组)。
    • 内部,我们构建了一个div元素,其中包含一个带有class="group"的“Select All Students”复选框。
    • group.map(studentName => ...).join("<br>"): 对于当前分组中的每个学生姓名,我们生成一个带有独立复选框的label元素,并用<br>标签分隔。
  • .join(""): 最后,将所有分组生成的HTML字符串连接成一个大的字符串,赋值给container元素的innerHTML。

4. 实现全选交互逻辑

最后一步是为“Select All Students”复选框添加交互功能。当用户点击这些复选框时,需要同步更新同组内所有学生复选框的状态。

document.querySelectorAll(".group").forEach(checkbox =>
  checkbox.addEventListener("click", () => {
    // 获取当前“Select All Students”复选框所在的父div
    const parentDiv = checkbox.closest("div");
    // 找到该div内所有的复选框(包括“Select All Students”本身和学生复选框)
    parentDiv.querySelectorAll("[type=checkbox]").forEach(childCheckbox => {
      // 将所有子复选框的状态设置为与“Select All Students”复选框相同
      childCheckbox.checked = checkbox.checked;
    });
  })
);
登录后复制

代码解析:

  • document.querySelectorAll(".group"): 选中所有带有class="group"的复选框(即所有的“Select All Students”复选框)。
  • .forEach(checkbox => { ... }): 遍历每个“Select All Students”复选框。
  • checkbox.addEventListener("click", () => { ... }): 为每个复选框添加点击事件监听器。
  • checkbox.closest("div"): closest()方法从当前元素开始,向上遍历DOM树,查找匹配指定选择器(div)的最近祖先元素。这确保我们只影响当前分组内的复选框。
  • parentDiv.querySelectorAll("[type=checkbox]"): 在当前分组的div内部,查找所有type="checkbox"的元素。
  • childCheckbox.checked = checkbox.checked;: 将所有找到的子复选框的checked属性设置为与触发事件的“Select All Students”复选框的checked属性相同。

5. 完整代码示例

为了使上述代码能够运行,我们需要一个HTML容器。

HTML (index.html):

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学生列表分组与全选功能</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        div { border: 1px solid #ccc; padding: 10px; margin-bottom: 15px; border-radius: 5px; }
        label { display: block; margin-bottom: 5px; }
    </style>
</head>
<body>
    <h1>学生列表分组与全选示例</h1>
    <div id="container">
        <!-- 动态生成的内容将在此处显示 -->
    </div>

    <script src="app.js"></script>
</body>
</html>
登录后复制

JavaScript (app.js):

const res = {
  List: [
    { "School information": { RegId: 1, Name: "SJ" }, ParentInfo: { Id: 0, Name: "Abc" }, Student: { Id: 1, Name: "Student1" } },
    { "School information": { RegId: 1, Name: "" }, ParentInfo: { Id: 0, Name: "" }, Student: { Id: 5, Name: "Student6" } },
    { "School information": { RegId: 1, Name: "" }, ParentInfo: { Id: 0, Name: "" }, Student: { Id: 1, Name: "Student3" } },
    { "School information": { RegId: 1, Name: "" }, ParentInfo: { Id: 0, Name: "" }, Student: { Id: 5, Name: "Student5" } },
    { "School information": { RegId: 1, Name: "" }, ParentInfo: { Id: 0, Name: "" }, Student: { Id: 1, Name: "Student4" } },
    { "School information": { RegId: 1, Name: "" }, ParentInfo: { Id: 0, Name: "" }, Student: { Id: 7, Name: "Student9" } },
    { "School information": { RegId: 1, Name: "" }, ParentInfo: { Id: 0, Name: "" }, Student: { Id: 7, Name: "Student11" } }
  ]
};

// 1. 数据分组
const groupedStudents = res.List.reduce((accumulator, currentItem) => {
    (accumulator[currentItem.Student.Id] ??= []).push(currentItem.Student.Name);
    return accumulator;
}, {});

// 2. 动态生成HTML
document.getElementById("container").innerHTML =
  Object.values(groupedStudents)
    .map(group =>
      '<div>' +
      '<label>Select All Studentds <input type="checkbox" class="group"></label><br>' +
      group.map(studentName => `<label><input type="checkbox">${studentName}</label>`).join("<br>") +
      '</div>'
    )
    .join("");

// 3. 实现全选交互逻辑
// 注意:事件监听器必须在HTML元素被添加到DOM后才能绑定
document.querySelectorAll(".group").forEach(checkbox =>
  checkbox.addEventListener("click", () => {
    const parentDiv = checkbox.closest("div");
    parentDiv.querySelectorAll("[type=checkbox]").forEach(childCheckbox => {
      childCheckbox.checked = checkbox.checked;
    });
  })
);
登录后复制

6. 总结与扩展思考

本教程演示了如何利用JavaScript的强大数组和对象方法,结合DOM操作,实现复杂的数据分组、动态UI渲染和交互功能。

关键技术点:

  • Array.prototype.reduce: 用于将列表数据聚合成更复杂的结构(如按键分组的对象)。
  • Object.values: 用于获取对象的所有值,便于后续的迭代处理。
  • Array.prototype.map: 用于将数据数组转换为HTML字符串数组
  • 空值合并赋值运算符 (??=): 简化了初始化数组的逻辑。
  • DOM操作: document.getElementById, document.querySelectorAll, element.closest, element.addEventListener是进行前端交互的基础。

注意事项与扩展:

  • 性能优化: 对于非常大的数据集,频繁操作innerHTML可能会有性能开销。可以考虑使用DOM片段(DocumentFragment)或虚拟DOM库(如React, Vue)来优化渲染性能。
  • 可访问性 (Accessibility): 在实际项目中,应确保生成的HTML符合可访问性标准,例如为复选框提供明确的for属性与id关联,以及适当的ARIA属性。
  • 错误处理: 在从后端获取数据时,应考虑数据可能为空或格式不正确的情况,并添加相应的错误处理逻辑。
  • 更复杂的UI: 如果需要更复杂的UI组件(如搜索、排序、分页),可以进一步封装这些逻辑,或利用成熟的前端框架。
  • 数据结构优化: 如果原始数据中包含更多需要展示的字段,可以在分组时将整个学生对象存储,而不是只存储姓名,以便后续渲染时访问更多信息。

通过掌握这些技术,开发者可以高效地处理和展示动态数据,构建响应式且用户友好的Web界面。

以上就是JavaScript中按ID分组数据并动态生成带有全选功能的学生列表的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门推荐
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号