萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

JavaScript 實現 HTML 表格客戶端排序:原生 JS、排序演算法與無障礙增強完整指南

核心邏輯:DOM 解析 → 資料提取 → 排序 → DOM 重構

客戶端表格排序適合**中小型資料集 (< 1000 列)**、靜態頁面、無後端 API 場景。大型資料集必須後端分頁排序。

原生 ES6+ 完整實作 (無依賴、可復用)

/**
 * 表格排序增強模組
 * 用法: new TableSorter(document.querySelector('table'), { numericColumns: [1,2] });
 */
class TableSorter {
  constructor(tableEl, options = {}) {
    this.table = tableEl;
    this.thead = tableEl.querySelector('thead');
    this.tbody = tableEl.querySelector('tbody');
    this.numericColumns = new Set(options.numericColumns || []); // 索引從 0 開始
    this.dateColumns = new Set(options.dateColumns || []);
    this.sortDirections = new Map(); // colIndex -> 'asc' | 'desc'
    this.init();
  }

  init() {
    if (!this.thead || !this.tbody) return;
    
    // 1. 為表頭添加排序按鈕與 ARIA
    [...this.thead.querySelectorAll('th')].forEach((th, colIndex) => {
      if (th.dataset.sortable === 'false') return; // 可選擇性禁用
      
      th.style.cursor = 'pointer';
      th.setAttribute('role', 'columnheader');
      th.setAttribute('aria-sort', 'none');
      th.tabIndex = 0; // 鍵盤可聚焦
      
      // 添加排序指示器
      const indicator = document.createElement('span');
      indicator.className = 'sort-indicator';
      indicator.setAttribute('aria-hidden', 'true');
      indicator.innerHTML = ' ⇅';
      th.appendChild(indicator);
      
      // 2. 綁定點擊與鍵盤事件
      th.addEventListener('click', () => this.sort(colIndex));
      th.addEventListener('keydown', (e) => {
        if (e.key === 'Enter' || e.key === ' ') {
          e.preventDefault();
          this.sort(colIndex);
        }
      });
    });
  }

  getCellValue(row, colIndex) {
    const cell = row.cells[colIndex];
    if (!cell) return '';
    
    // 優先取 data-sort-value (精確排序值),其次 textContent
    const sortValue = cell.dataset.sortValue ?? cell.textContent.trim();
    
    // 數值欄位:解析為數字 (處理千分位、貨幣符號、百分比)
    if (this.numericColumns.has(colIndex)) {
      const num = parseFloat(sortValue.replace(/[^\d.-]/g, ''));
      return isNaN(num) ? -Infinity : num; // 非數字排最後
    }
    
    // 日期欄位:解析為時間戳
    if (this.dateColumns.has(colIndex)) {
      // 支援 ISO, YYYY/MM/DD, YYYY-MM-DD, MM/DD/YYYY 等常見格式
      const date = new Date(sortValue.replace(/(\d{2})\/(\d{2})\/(\d{4})/, '$3-$1-$2'));
      return isNaN(date.getTime()) ? -Infinity : date.getTime();
    }
    
    // 文字欄位:區域敏感比較
    return sortValue;
  }

  sort(colIndex) {
    const rows = [...this.tbody.rows];
    const isAsc = this.sortDirections.get(colIndex) !== 'asc'; // 切換方向
    this.sortDirections.set(colIndex, isAsc ? 'asc' : 'desc');
    
    // 更新所有表頭 ARIA 狀態
    [...this.thead.querySelectorAll('th')].forEach((th, i) => {
      th.setAttribute('aria-sort', i === colIndex ? (isAsc ? 'ascending' : 'descending') : 'none');
    });
    
    // 3. 排序核心:Intl.Collator 正確處理多語言、數字、符號
    const collator = new Intl.Collator(undefined, { 
      numeric: true,           // 數字感知排序 ( "2" < "10" )
      sensitivity: 'base',     // 忽略大小寫、重音
      ignorePunctuation: true  // 忽略標點
    });
    
    rows.sort((rowA, rowB) => {
      const valA = this.getCellValue(rowA, colIndex);
      const valB = this.getCellValue(rowB, colIndex);
      
      let result;
      if (typeof valA === 'number' && typeof valB === 'number') {
        result = valA - valB;
      } else if (typeof valA === 'number') result = -1; // 數字優先
      else if (typeof valB === 'number') result = 1;
      else result = collator.compare(String(valA), String(valB));
      
      return isAsc ? result : -result;
    });
    
    // 4. DOM 重構:使用 DocumentFragment 批量操作,避免多次重排
    const fragment = document.createDocumentFragment();
    rows.forEach(row => fragment.appendChild(row));
    this.tbody.appendChild(fragment);
    
    // 5. 觸發自定義事件,供外部擴展 (如更新分頁、動畫)
    this.table.dispatchEvent(new CustomEvent('tablesorted', { 
      detail: { column: colIndex, direction: isAsc ? 'asc' : 'desc' } 
    }));
  }
  
  // 公開方法:程式化觸發排序
  sortColumn(colIndex, direction = 'asc') {
    this.sortDirections.set(colIndex, direction === 'asc' ? 'desc' : 'asc'); // 反向以便 sort() 翻轉
    this.sort(colIndex);
  }
}

// 自動啟動:所有帶 data-sortable="true" 的表格
document.addEventListener('DOMContentLoaded', () => {
  document.querySelectorAll('table[data-sortable="true"]').forEach(table => {
    new TableSorter(table);
  });
});

HTML 結構要求

<table class="sortable-table" data-sortable="true">
  <thead>
    <tr>
      <th>姓名</th>
      <th data-sortable="false">操作</th> <!-- 禁用排序 -->
      <th class="numeric-col">年齡</th>
      <th class="numeric-col">薪資</th>
      <th class="date-col">入職日期</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>張三</td>
      <td><button>編輯</button></td>
      <td data-sort-value="28">28 歲</td> <!-- 精確排序值 -->
      <td data-sort-value="55000">NT$ 55,000</td>
      <td data-sort-value="2020-03-15">2020/03/15</td>
    </tr>
    <tr>
      <td>李四</td>
      <td><button>編輯</button></td>
      <td data-sort-value="35">35 歲</td>
      <td data-sort-value="72000">NT$ 72,000</td>
      <td data-sort-value="2018-07-01">2018/07/01</td>
    </tr>
  </tbody>
</table>

CSS 樣式:排序指示器與狀態

.sortable-table th[role="columnheader"] {
  user-select: none;
  white-space: nowrap;
  position: relative;
  padding-right: 28px; /* 為指示器留空間 */
}

.sort-indicator {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 0.75em;
  color: #999;
  transition: transform 0.2s, color 0.2s;
}

/* 排序狀態樣式 */
th[aria-sort="ascending"] .sort-indicator { transform: translateY(-50%) rotate(180deg); color: #0066cc; }
th[aria-sort="descending"] .sort-indicator { transform: translateY(-50%) rotate(0deg); color: #0066cc; }
th[aria-sort="none"] .sort-indicator { color: #ccc; }

/* 懸停/焦點回饋 */
th[role="columnheader"]:hover .sort-indicator,
th[role="columnheader"]:focus .sort-indicator { color: #0066cc; }

進階功能擴展

1. 多欄位排序 (Shift + Click)

// 在 TableSorter 中擴展
this.sortKeys = []; // [{colIndex, direction}]

th.addEventListener('click', (e) => {
  if (e.shiftKey && this.sortKeys.length) {
    // 多欄排序:添加為次要鍵
    const existing = this.sortKeys.find(k => k.colIndex === colIndex);
    if (existing) existing.direction = isAsc ? 'asc' : 'desc';
    else this.sortKeys.push({colIndex, direction: isAsc ? 'asc' : 'desc'});
    this.multiSort();
  } else {
    this.sortKeys = [{colIndex, direction: isAsc ? 'asc' : 'desc'}];
    this.sort(colIndex);
  }
});

multiSort() {
  const rows = [...this.tbody.rows];
  const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
  
  rows.sort((a, b) => {
    for (const {colIndex, direction} of this.sortKeys) {
      const valA = this.getCellValue(a, colIndex);
      const valB = this.getCellValue(b, colIndex);
      let cmp = (typeof valA === 'number' && typeof valB === 'number') 
        ? valA - valB : collator.compare(String(valA), String(valB));
      if (cmp !== 0) return direction === 'asc' ? cmp : -cmp;
    }
    return 0;
  });
  // ... DOM 重構同單欄
}

2. 搭配虛擬滾動 / 分頁

若資料 > 500 列,建議:

  • **後端排序 + 分頁 API** (標準做法)。
  • 前端虛擬滾動庫:tanstack/virtual, react-window, vue-virtual-scroller。
  • 若必須前端全量排序:使用 **Web Worker** 計算排序順序,主線程只做 DOM 更新。

3. 整合 DataTables / AG Grid 等專業庫

企業級應用需求(分頁、篩選、匯出、編輯、分組、樹狀表格)強烈建議直接使用成熟庫:

  • AG Grid (Community 免費功能極強)
  • TanStack Table (React Table v8) Headless, 框架無關
  • DataTables jQuery 經典,零依賴版亦可用

效能優化檢查清單

  1. 使用 data-sort-value 避免重複解析格式化字串 (貨幣、日期)。
  2. DocumentFragment 批量 DOM 移動,單次 Reflow。
  3. Intl.Collator 重用實例,避免排序比較函數內重複創建。
  4. 事件委派:表頭事件綁定在 thead 上,判斷 e.target.closest('th')。
  5. 防抖:若綁定即時搜尋/篩選聯動排序,對排序觸發加 debounce(150ms)。
  6. 虛擬化:大數據集唯一出路。

無障礙合規 (WCAG 2.1 AA)

  • th[role="columnheader"] + aria-sort 狀態正確更新。
  • tabIndex=0 + keydown Enter/Space 觸發排序,鍵盤完整可操作。
  • 排序指示器 aria-hidden="true",避免重複朗讀。
  • 排序完成後 aria-live="polite" 宣告「已按薪資升序排序」等狀態變化。

掌握原生 JS 表格排序核心邏輯,能讓你在無法引入重型庫的輕量專案中快速交付專業級體驗;而在複雜業務中,果斷選擇成熟庫並理解其底層原理,才是架構師的智慧。

copyright © 萬盛學電腦網 all rights reserved