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

使用JavaScript同一函数实现双表格联动排序需修改哪些现有代码

实现双表格同步排序的修改方案

核心修改点

  • 原代码的表头点击事件仅对当前点击的表格执行排序,需要改为点击后遍历所有带table-sortable类的表格,统一应用相同的排序规则(排序列、升降序)
  • 排序状态标识类(th-sort-asc/th-sort-desc)会同步更新到所有表格对应列的表头,保证显示状态一致

修改后的完整JS代码

function sortTable(table, column, asc = true) {
        const dirModifier = asc ? 1 : -1;
        const tBody = table.tBodies[0];
        const rows = Array.from(tBody.querySelectorAll("tr"));
    
        const sortedRows = rows.sort((a, b) => {
            const aColText = a.querySelector(`td:nth-child(${ column + 1 })`).textContent.trim();
            const bColText = b.querySelector(`td:nth-child(${ column + 1 })`).textContent.trim();
    
            return aColText > bColText ? (1 * dirModifier) : (-1 * dirModifier);
        });
    
        while (tBody.firstChild) {
            tBody.removeChild(tBody.firstChild);
        }
    
        tBody.append(...sortedRows);
    
        table.querySelectorAll("th").forEach(th => th.classList.remove("th-sort-asc", "th-sort-desc"));
        table.querySelector(`th:nth-child(${ column + 1})`).classList.toggle("th-sort-asc", asc);
        table.querySelector(`th:nth-child(${ column + 1})`).classList.toggle("th-sort-desc", !asc);
    }
    
document.querySelectorAll(".table-sortable th").forEach(headerCell => {
    headerCell.addEventListener("click", () => {
        const headerIndex = Array.prototype.indexOf.call(headerCell.parentElement.children, headerCell);
        const currentIsAscending = headerCell.classList.contains("th-sort-asc");
        // 遍历所有待排序表格统一执行排序逻辑
        const allSortableTables = document.querySelectorAll(".table-sortable");
        allSortableTables.forEach(table => {
            sortTable(table, headerIndex, !currentIsAscending);
        });
    });
});

可选优化(仅点击name列才同步排序)

如果不需要所有列都同步,仅要求点击name列表头时才触发双表同步,其他列仅排序当前点击的表格,可以调整点击事件逻辑:

headerCell.addEventListener("click", () => {
    const headerIndex = Array.prototype.indexOf.call(headerCell.parentElement.children, headerCell);
    const currentIsAscending = headerCell.classList.contains("th-sort-asc");
    const headerText = headerCell.textContent.trim();
    const currentTable = headerCell.closest('table');
    // 仅name列同步排序
    if(headerText === 'name') {
        const allSortableTables = document.querySelectorAll(".table-sortable");
        allSortableTables.forEach(table => {
            sortTable(table, headerIndex, !currentIsAscending);
        });
    } else {
        sortTable(currentTable, headerIndex, !currentIsAscending);
    }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 02:57:03