如何使用JavaScript遍历嵌套HTML表格列表头生成路径
遍历嵌套表头生成列路径字符串的方法
问题场景
我有一个表头层级长度不一的嵌套HTML表格(示例如下),需要为每一列向上遍历表头,生成对应的路径字符串(例如“Overall>Score”“Company System>Ethnicity>Hispanic or Latino>vs. Company”等),用jQuery尝试后无法实现,求可行的遍历方法。
示例表格代码:
<table id="fakeTableID"> <thead> <tr><td rowspan="4">#</td><td rowspan="1" colspan="1">Overall </td><td colspan="3" rowspan="1" style="text-align:center">Company System</td></tr> <tr><td rowspan="3" colspan="1"> Score</td><td colspan="3" rowspan="1" style="text-align:center">Ethnicity</td></tr> <tr><td rowspan="1" colspan="1">Hispanic or Latino</td><td rowspan="1" colspan="1">Non-Hispanic or Latino</td><td rowspan="1" colspan="1">Prefer not to answer</td></tr> <tr><td rowspan="1" colspan="1">vs. Company</td><td rowspan="1" colspan="1">vs. Company</td><td rowspan="1" colspan="1">vs. Company</td></tr> </thead> <tbody> <tr> <td>test </td> <td>2.95</td> <td>-</td> <td>-</td> <td>-</td> </tr> <tr> <td>test </td> <td>3.02</td> <td>-</td> <td>-</td> <td>-</td> </tr> <tr> <td>test </td> <td>3.08</td> <td>-</td> <td>-</td> <td>-</td> </tr> </tbody> </table>
解决方案
核心思路是先确定每一列对应的所有表头单元格,处理rowspan和colspan的跨行列逻辑,再按层级拼接文本。以下是实现代码:
$(document).ready(function() { const $table = $('#fakeTableID'); const $theadRows = $table.find('thead tr'); const totalColumns = $table.find('tbody tr:first td').length; const columnPaths = []; // 遍历每一列 for (let colIndex = 0; colIndex < totalColumns; colIndex++) { const headers = []; let currentCol = colIndex; // 从最后一行表头向上遍历,按层级收集表头文本 for (let rowIndex = $theadRows.length - 1; rowIndex >= 0; rowIndex--) { const $cells = $theadRows.eq(rowIndex).find('td'); let cellIndex = 0; let found = false; while (cellIndex < $cells.length && !found) { const $cell = $cells.eq(cellIndex); const colspan = parseInt($cell.attr('colspan')) || 1; const rowspan = parseInt($cell.attr('rowspan')) || 1; // 判断当前单元格是否覆盖目标列 if (currentCol >= cellIndex && currentCol < cellIndex + colspan) { // 去重避免rowspan重复添加相同文本 const text = $.trim($cell.text()); if (!headers.includes(text)) { headers.unshift(text); } found = true; } else { // 单元格不覆盖目标列,累加colspan调整列位置 cellIndex += colspan; } } } // 拼接成路径字符串 columnPaths.push(headers.join('>')); } // 输出结果,可按需替换为业务逻辑 console.log(columnPaths); // 输出示例:["#", "Overall> Score", "Company System>Ethnicity>Hispanic or Latino>vs. Company", "Company System>Ethnicity>Non-Hispanic or Latino>vs. Company", "Company System>Ethnicity>Prefer not to answer>vs. Company"] });
代码说明
- 先获取表格、表头行和总列数,总列数通过tbody第一行的单元格数量确定
- 遍历每一列,从最底层表头向上遍历每一行,定位当前列对应的表头单元格
- 处理
colspan:若当前单元格不覆盖目标列,累加colspan值调整列位置 - 处理
rowspan:通过去重避免同一表头文本被重复添加 - 将收集到的表头文本按层级拼接成路径字符串,存入数组
内容的提问来源于stack exchange,提问作者user361510
相关产品推荐
相关产品推荐

