萬盛學電腦網

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

HTML 表格前端排序實作:jQuery 方案與現代原生實現

表格資料前端排序:從 jQuery 到原生 JS 完整遷移指南

表格排序是數據展示的常見需求。早期常用 jQuery 插件,現代瀏覽器原生 API 已足夠強大,無需額外依賴。

jQuery 經典實作(參考遷移)

// 原始碼重構版:可讀性優化
function sortTable($table, columnIndex, isNumeric = false) {
  const $rows = $table.find('tbody tr').get();
  
  $rows.sort((a, b) => {
    const aText = $(a).find('td').eq(columnIndex).text().trim();
    const bText = $(b).find('td').eq(columnIndex).text().trim();
    
    const aVal = isNumeric ? parseFloat(aText) : aText;
    const bVal = isNumeric ? parseFloat(bText) : bText;
    
    if (aVal < bVal) return -1;
    if (aVal > bVal) return 1;
    return 0;
  });
  
  $.each($rows, (i, row) => $table.find('tbody').append(row));
}

// 綁定表頭點擊
$('table th').click(function() {
  const $th = $(this);
  const index = $th.index();
  const isNum = $th.data('type') === 'number';
  const asc = !$th.hasClass('sort-asc');
  
  $th.siblings().removeClass('sort-asc sort-desc');
  $th.toggleClass('sort-asc', asc).toggleClass('sort-desc', !asc);
  
  sortTable($th.closest('table'), index, isNum);
  
  if (!asc) {
    // 降序:反轉陣列
    const $tbody = $th.closest('table').find('tbody');
    const $rows = $tbody.find('tr').get().reverse();
    $tbody.append($rows);
  }
});

現代原生 JS 實作(零依賴、效能更好)

class TableSorter {
  constructor(tableEl, options = {}) {
    this.table = tableEl;
    this.tbody = tableEl.querySelector('tbody');
    this.headers = tableEl.querySelectorAll('th[data-sort]');
    this.sortDirections = new Map();
    this.init();
  }
  
  init() {
    this.headers.forEach((th, idx) => {
      th.style.cursor = 'pointer';
      th.addEventListener('click', () => this.sort(idx, th.dataset.type));
      // 添加排序指示器
      th.innerHTML += ' <span class="sort-indicator">⇅</span>';
    });
  }
  
  sort(columnIndex, type = 'text') {
    const rows = Array.from(this.tbody.rows);
    const isAsc = this.sortDirections.get(columnIndex) !== 'asc';
    this.sortDirections.set(columnIndex, isAsc ? 'asc' : 'desc');
    
    // 更新所有表頭指示器
    this.headers.forEach((th, i) => {
      const ind = th.querySelector('.sort-indicator');
      if (i === columnIndex) {
        ind.textContent = isAsc ? '↑' : '↓';
        ind.className = 'sort-indicator active';
      } else {
        ind.textContent = '⇅';
        ind.className = 'sort-indicator';
      }
    });
    
    rows.sort((a, b) => {
      const aText = a.cells[columnIndex]?.textContent.trim() || '';
      const bText = b.cells[columnIndex]?.textContent.trim() || '';
      
      let aVal = type === 'number' ? parseFloat(aText) : aText;
      let bVal = type === 'number' ? parseFloat(bText) : bText;
      
      // 處理 NaN
      if (isNaN(aVal)) aVal = type === 'number' ? -Infinity : '';
      if (isNaN(bVal)) bVal = type === 'number' ? -Infinity : '';
      
      const cmp = aVal < bVal ? -1 : aVal > bVal ? 1 : 0;
      return isAsc ? cmp : -cmp;
    });
    
    // 重新插入(觸發重排一次)
    const fragment = document.createDocumentFragment();
    rows.forEach(row => fragment.appendChild(row));
    this.tbody.appendChild(fragment);
  }
}

// 初始化
document.querySelectorAll('table.sortable').forEach(table => {
  new TableSorter(table);
});

HTML 結構要求

<table class="sortable">
  <thead>
    <tr>
      <th data-sort data-type="text">姓名</th>
      <th data-sort data-type="number">分數</th>
      <th data-sort data-type="date">日期</th>
    </tr>
  </thead>
  <tbody>
    <tr><td>張三</td><td>95.5</td><td>2024-01-15</td></tr>
    <tr><td>李四</td><td>87</td><td>2024-01-10</td></tr>
  </tbody>
</table>

進階功能擴展

// 多欄位排序(Shift+點擊)
th.addEventListener('click', e => {
  if (e.shiftKey) {
    this.addSortLevel(columnIndex, type);
  } else {
    this.sort(columnIndex, type);
  }
});

// 日期類型支援
const parseDate = (str) => {
  const [y, m, d] = str.split(/[-/]/).map(Number);
  return new Date(y, (m||1)-1, d||1).getTime();
};

// 在 sort 中加入 type === 'date' 分支
// aVal = parseDate(aText) || -Infinity;

效能優化建議

  • 使用 DocumentFragment 批次 DOM 操作
  • 大量資料(>1000 行)考慮虛擬滾動或分頁
  • 排序函數避免重複計算,可預先解析緩存
  • 防抖處理快速連續點擊

無障礙排序表格

  • aria-sort="ascending|descending|none" 標示當前排序狀態
  • aria-label="按姓名排序,升序" 提供語音提示
  • 鍵盤可操作:th 加 tabindex="0" + Enter/Space 觸發

原生實作不僅輕量,更能完全掌控排序邏輯與無障礙體驗。

copyright © 萬盛學電腦網 all rights reserved