表格排序是數據展示的常見需求。早期常用 jQuery 插件,現代瀏覽器原生 API 已足夠強大,無需額外依賴。
// 原始碼重構版:可讀性優化
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);
}
});
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);
});
<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 操作aria-sort="ascending|descending|none" 標示當前排序狀態aria-label="按姓名排序,升序" 提供語音提示th 加 tabindex="0" + Enter/Space 觸發原生實作不僅輕量,更能完全掌控排序邏輯與無障礙體驗。