本文提供一個功能更完善、程式碼結構更清晰的原生 JavaScript 表格排序元件,支援**多資料型別自動偵測、千分位數字、日期、自定義比較器、鍵盤無障礙、狀態保持**、並提供 TypeScript 型別定義方便現代專案整合。
localeCompare 中文排序)。無序 → 升冊 → 降冊,視覺指示器 (SVG 箭頭) 自動切換。getValue 提取比較值、comparator 自定義比較邏輯。localStorage,重新整理保持。<!-- 1. 引入樣式 (可自行覆寫) -->
<link rel="stylesheet" href="table-sort.css">
<!-- 2. 引入腳本 (ES Module 或 UMD) -->
<script type="module">
import TableSort from './table-sort.js';
// 或 UMD: const TableSort = window.TableSort;
</script>
<table id="userTable" class="sortable-table">
<thead>
<tr>
<th data-sort="string">姓名</th>
<th data-sort="number">年齡</th>
<th data-sort="date">加入日期</th>
<th data-sort="number" data-sort-format="currency">薪資</th>
<th>備註 (不可排序)</th> <!-- 無 data-sort 則不可排序 -->
</tr>
</thead>
<tbody>
<tr><td>陳小明</td><td>28</td><td>2023-05-12</td><td>$45,000</td><td>工程師</td></tr>
<tr><td>林大華</td><td>35</td><td>2021-11-03</td><td>$62,500</td><td>主管</td></tr>
<tr><td>王美麗</td><td>24</td><td>2024-01-15</td><td>$38,000</td><td>設計師</td></tr>
</tbody>
</table>
關鍵點:
<thead> + <tbody>** 結構,元件僅排序 tbody 內列。data-sort 屬性明確宣告型別:string, number, date, currency (自動移除 $, 逗號)。data-sort 的 <th> 不綁定事件,保持靜態。// table-sort.js
export default class TableSort {
/**
* @param {string|HTMLTableElement} table - 表格 ID 或元素
* @param {Object} options - 選項
* @param {boolean} options.persist - 是否持久化排序狀態到 localStorage
* @param {Function} options.onSort - 排序完成回調 (sortedColumnIndex, direction)
*/
constructor(table, options = {}) {
this.table = typeof table === 'string' ? document.getElementById(table) : table;
if (!this.table || this.table.tagName !== 'TABLE') throw new Error('Invalid table element');
this.options = { persist: false, onSort: null, ...options };
this.sortState = { column: null, direction: 'none' }; // 'asc' | 'desc' | 'none'
this._init();
}
_init() {
this.thead = this.table.querySelector('thead');
this.tbody = this.table.querySelector('tbody');
if (!this.thead || !this.tbody) throw new Error('Table must have and ');
this.headers = Array.from(this.thead.querySelectorAll('th[data-sort]'));
this._bindEvents();
this._restoreState();
this._renderHeaders();
}
_bindEvents() {
this.headers.forEach((th, index) => {
th.style.cursor = 'pointer';
th.setAttribute('role', 'columnheader');
th.setAttribute('aria-sort', 'none');
th.setAttribute('tabindex', '0');
const handleClick = () => this._sort(index);
const handleKey = (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); this._sort(index); } };
th.addEventListener('click', handleClick);
th.addEventListener('keydown', handleKey);
// 存儲監聽器以便銷毀
th._sortHandlers = { click: handleClick, keydown: handleKey };
});
}
_sort(columnIndex) {
const th = this.headers[columnIndex];
const type = th.dataset.sort;
const format = th.dataset.sortFormat;
// 切換方向: none -> asc -> desc -> none (可選,這裡採雙態循環)
let direction = this.sortState.column === columnIndex && this.sortState.direction === 'asc' ? 'desc' : 'asc';
if (this.sortState.column === columnIndex && this.sortState.direction === 'desc') direction = 'asc'; // 或重置為 none
this.sortState = { column: columnIndex, direction };
this._renderHeaders();
this._sortRows(type, format, direction);
this._persistState();
this.options.onSort?.(columnIndex, direction);
}
_sortRows(type, format, direction) {
const rows = Array.from(this.tbody.rows);
const colIndex = this.sortState.column;
rows.sort((a, b) => {
const valA = this._getCellValue(a.cells[colIndex], type, format);
const valB = this._getCellValue(b.cells[colIndex], type, format);
let cmp = 0;
if (valA === valB) cmp = 0;
else if (valA === null || valA === undefined) cmp = 1; // null 後排
else if (valB === null || valB === undefined) cmp = -1;
else if (typeof valA === 'number' && typeof valB === 'number') cmp = valA - valB;
else if (valA instanceof Date && valB instanceof Date) cmp = valA - valB;
else cmp = String(valA).localeCompare(String(valB), undefined, { numeric: true, sensitivity: 'base' });
return direction === 'asc' ? cmp : -cmp;
});
// 重新附加到 tbody (DocumentFragment 效能更好)
const fragment = document.createDocumentFragment();
rows.forEach(row => fragment.appendChild(row));
this.tbody.appendChild(fragment);
}
_getCellValue(cell, type, format) {
if (!cell) return null;
let text = cell.textContent.trim();
if (!text) return null;
// 自定義提取器 (掛在元件實例上)
if (this.options.getValue) return this.options.getValue(cell, type, format);
switch (type) {
case 'number':
if (format === 'currency') text = text.replace(/[^0-9.-]/g, '');
return parseFloat(text.replace(/,/g, ''));
case 'date':
// 支援 YYYY-MM-DD, YYYY/MM/DD, MM/DD/YYYY 等常見格式
const parts = text.split(/[-/\.]/);
if (parts.length === 3) {
const [y, m, d] = parts.length === 3 && parts[0].length === 4 ? [parts[0], parts[1], parts[2]] : [parts[2], parts[0], parts[1]];
const date = new Date(y, m - 1, d);
return isNaN(date) ? text : date;
}
const date = new Date(text);
return isNaN(date) ? text : date;
case 'string':
default:
return text;
}
}
_renderHeaders() {
this.headers.forEach((th, i) => {
th.classList.remove('sort-asc', 'sort-desc', 'sort-none');
th.removeAttribute('aria-sort');
if (i === this.sortState.column) {
th.classList.add(this.sortState.direction === 'asc' ? 'sort-asc' : 'sort-desc');
th.setAttribute('aria-sort', this.sortState.direction === 'asc' ? 'ascending' : 'descending');
} else {
th.classList.add('sort-none');
th.setAttribute('aria-sort', 'none');
}
});
}
_persistState() {
if (!this.options.persist) return;
const key = `tableSort_${this.table.id || 'default'}`;
localStorage.setItem(key, JSON.stringify(this.sortState));
}
_restoreState() {
if (!this.options.persist) return;
const key = `tableSort_${this.table.id || 'default'}`;
const saved = localStorage.getItem(key);
if (saved) {
try {
this.sortState = JSON.parse(saved);
if (this.sortState.column !== null && this.headers[this.sortState.column]) {
this._sortRows(
this.headers[this.sortState.column].dataset.sort,
this.headers[this.sortState.column].dataset.sortFormat,
this.sortState.direction
);
}
} catch (e) { console.warn('Restore sort state failed', e); }
}
}
// 公開方法:銷毀實例,移除事件監聽
destroy() {
this.headers.forEach(th => {
th.removeEventListener('click', th._sortHandlers.click);
th.removeEventListener('keydown', th._sortHandlers.keydown);
th.removeAttribute('role');
th.removeAttribute('aria-sort');
th.removeAttribute('tabindex');
th.style.cursor = '';
th.classList.remove('sort-asc', 'sort-desc', 'sort-none');
});
}
}
CSS 樣式 (table-sort.css)
.sortable-table { border-collapse: collapse; width: 100%; }
.sortable-table th { position: relative; padding-right: 24px; /* 留空間給箭頭 */ user-select: none; }
.sortable-table th::after {
content: ''; position: absolute; right: 8px; top: 50%; transform: translateY(-50%);
width: 0; height: 0; border-left: 5px solid transparent; border-right: 5px solid transparent; opacity: 0.3;
transition: opacity 0.2s, transform 0.2s;
}
.sortable-table th.sort-none::after { border-bottom: 6px solid #666; } /* 向下三角 = 未排序 */
.sortable-table th.sort-asc::after { border-top: 6px solid #0066cc; opacity: 1; } /* 向上三角 = 升冊 */
.sortable-table th.sort-desc::after { border-bottom: 6px solid #0066cc; opacity: 1; } /* 向下三角 = 降冊 */
.sortable-table th:hover::after { opacity: 0.6; }
.sortable-table th:focus { outline: 2px solid #0066cc; outline-offset: -2px; z-index: 1; }
初始化與進階用法
<script type="module">
import TableSort from './table-sort.js';
// 基本初始化
const sorter = new TableSort('userTable', {
persist: true, // 記住排序狀態
onSort: (col, dir) => console.log(`Sorted column ${col} ${dir}`)
});
// 進階:自定義比較值提取 (例如儲存格包含隱藏 data-value)
sorter.options.getValue = (cell, type, format) => {
if (cell.dataset.sortValue !== undefined) return cell.dataset.sortValue;
return null; // 返回 null 表示使用預設邏輯
};
// 進階:動態新增資料後重新綁定 (若 tbody 內容被替換)
// sorter.destroy(); new TableSort('userTable', options); // 簡單重建即可
</script>
遷移舊版程式碼 (prototype 寫法) 的建議
原始碼採用 ES5 prototype 寫法,存在 this 綁定問題、全域汙染、無模組化、無無障礙支援。建議:
- 直接替換為上述 ES6 Class 版本。
2. 若專案仍用舊環境,使用 Babel 轉譯或手動改寫為 IIFE 模組模式。
3. 移除舊版依賴的 killHTML, Bind, addEventListener 等自製工具函式,改用原生 textContent, addEventListener, 箭頭函式。
結語
現代表格排序元件應具備:型別安全、無障礙、效能導向、易擴充、樣式分離。本文提供的 ES6 Class 實作滿足上述條件,可直接投入生產環境或作為學習現代前端元件設計的範本。
- 上一篇程序編程: HTML 表格對齊與間距屬性完整指南:從舊屬性到現代 CSS 最佳實踐
- 下一篇程序編程: HTML 表格寬度控制實戰:CSS 固定佈局、溢出處理與響應式策略
HTML5 教學排行
推薦文章
- HTML5 <video> 完全指南:格式兼容、屬性詳解與多源碼落地實踐
- HTML <button> 按鈕樣式完全指南:原生重置、狀態設計、無障礙與框架整…
- HTML 表格垂直置頂對齊的實作技巧
- H5 設計全攻略:字體、排版、動效、音效、適配與創意發想實戰指南
- HTML 多行註解語法與實務應用:區塊標記、條件編譯、工具指令
- HTML 是什麼語言?超文本標記語言本質、結構組成、編寫工具與入門範例完整解析
- HTML 表格背景色設定:bgcolor 屬性與 CSS background-…
- HTML 代碼基本結構與通用格式詳解
- HTML <hr> 水平線樣式大全:border-top 打造多種視覺效果
- 深度解析 HTML5:12 個核心資源助你搶先佈局下一代 Web
copyright © 萬盛學電腦網 all rights reserved