如何基于每行指定列的内容将单个大表格拆分为多个独立子表
表格按列值拆分实现方案
以下是可直接使用的油猴脚本实现:
// ==UserScript== // @name 按列值拆分表格 // @namespace http://www.w3schools.com/ // @description 根据指定列的不同值自动拆分表格 // @include 替换为你要应用脚本的页面URL // @require http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js // @version 1 // ==/UserScript== $(function(){ // 可自定义配置项 const splitColumnIndex = 0; // 用于拆分的目标列索引,从0开始计数,第一列即为0 const removeTypeColumn = true; // 设为true时移除类型列、表格前展示类型标题,设为false保留原结构 const renderDelay = 3000; // 页面加载后延迟执行的时间,单位毫秒,页面加载慢可适当调大 setTimeout(function(){ const $originalTable = $("table").eq(0); // 取页面第一个表格,多表格场景可调整选择器 const $headerRow = $originalTable.find("tr:first").clone(); const rowGroups = {}; // 遍历所有数据行,按指定列值分组 $originalTable.find("tr:not(:first)").each(function(){ const typeVal = $(this).find(`td:eq(${splitColumnIndex})`).text().trim(); if(!rowGroups[typeVal]) rowGroups[typeVal] = []; rowGroups[typeVal].push($(this).clone()); }); // 移除原表格 $originalTable.remove(); // 遍历分组生成新表格 Object.keys(rowGroups).forEach(type => { const $newTable = $("<table><tbody></tbody></table>"); let $newHeader = $headerRow.clone(); let rows = rowGroups[type].map(row => row.clone()); // 开启移除类型列逻辑 if(removeTypeColumn) { $newHeader.find(`th:eq(${splitColumnIndex}), td:eq(${splitColumnIndex})`).remove(); rows.forEach(row => row.find(`td:eq(${splitColumnIndex})`).remove()); // 表格前加类型标题 $(`<h3>${type}</h3>`).insertBefore($newTable); } // 组装表格 $newTable.find("tbody").append($newHeader).append(rows); $("body").append($newTable); }); }, renderDelay); });
使用说明
- 先替换脚本头部
@include的内容为你需要使用脚本的目标页面地址 - 按需调整配置项参数:如果要按第二列拆分就把
splitColumnIndex改成1,不需要移除类型列就把removeTypeColumn改成false - 脚本依赖jQuery,已经在头部引入无需额外处理
内容的提问来源于stack exchange,提问作者Kabaneru
相关产品推荐
相关产品推荐

