首页app攻略js中获取id名 js根据id获取标签

js中获取id名 js根据id获取标签

圆圆2025-09-01 00:00:36次浏览条评论

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;}, {}); // 初始累加器为一个空对象
登录后复制

代码解析:

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. 动态生成HTMLdocument.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分组数据并动态生成带有全选功能的学生列表的详细内容,更多请关注乐哥常识网其它相关文章!

JavaScript
POSTGRESQL语句 postgresql语句中表格怎么表示
相关内容
发表评论

游客 回复需填写必要信息