讓使用者點擊表格標題欄即可對該欄資料進行升冪/降冪排序,支援數字、文字、日期等多種型別,純前端實現,無需後端配合。
<table> 參考,取得表頭 <th> 與資料列 <tr>[[cell1, cell2...], [...]] 方便排序<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<title>可排序表格 Demo</title>
<style>
table { border-collapse: collapse; margin: 2rem auto; font-family: sans-serif; }
th, td { border: 1px solid #ddd; padding: 8px 12px; text-align: center; }
th { background: #f0f0f0; cursor: pointer; user-select: none; }
th.sort-asc::after { content: " ▲"; }
th.sort-desc::after { content: " ▼"; }
tbody tr:hover { background: #f9f9f9; }
</style>
</head>
<body>
<table id="data-table">
<thead>
<tr>
<th data-type="string">產品</th>
<th data-type="number">價格</th>
<th data-type="number">庫存</th>
<th data-type="date">上架日期</th>
</tr>
</thead>
<tbody>
<tr><td>筆電</td><td>25,900</td><td>12</td><td>2024-01-15</td></tr>
<tr><td>滑鼠</td><td>590</td><td>150</td><td>2023-11-20</td></tr>
<tr><td>螢幕</td><td>8,500</td><td>8</td><td>2024-03-01</td></tr>
<tr><td>鍵盤</td><td>1,200</td><td>45</td><td>2023-12-10</td></tr>
</tbody>
</table>
<script>
(function() {
const table = document.getElementById('data-table');
const headers = table.querySelectorAll('th');
const tbody = table.querySelector('tbody');
let sortDirections = {}; // 記錄每欄排序方向
// 1. 將 tbody 所有 tr 轉為陣列
const rows = Array.from(tbody.rows);
// 2. 綁定點擊事件
headers.forEach((th, colIndex) => {
th.addEventListener('click', () => sortTable(colIndex, th));
});
function sortTable(colIndex, th) {
// 切換方向
const currentDir = sortDirections[colIndex] || 'asc';
const newDir = currentDir === 'asc' ? 'desc' : 'asc';
sortDirections[colIndex] = newDir;
// 更新 UI 箭頭
headers.forEach(h => h.classList.remove('sort-asc', 'sort-desc'));
th.classList.add(newDir === 'asc' ? 'sort-asc' : 'sort-desc');
// 取得型別
const type = th.dataset.type || 'string';
// 3. 排序
rows.sort((a, b) => {
let valA = a.cells[colIndex].textContent.trim();
let valB = b.cells[colIndex].textContent.trim();
// 清理數字格式
if (type === 'number') {
valA = parseFloat(valA.replace(/,/g, ''));
valB = parseFloat(valB.replace(/,/g, ''));
return newDir === 'asc' ? valA - valB : valB - valA;
}
if (type === 'date') {
valA = new Date(valA).getTime();
valB = new Date(valB).getTime();
return newDir === 'asc' ? valA - valB : valB - valA;
}
// 字串 localeCompare
return newDir === 'asc'
? valA.localeCompare(valB, 'zh-Hant')
: valB.localeCompare(valA, 'zh-Hant');
});
// 4. 重新掛載到 DOM
rows.forEach(row => tbody.appendChild(row));
}
})();
</script>
</body>
</html>
| 函式/步驟 | 說明 |
|---|---|
Array.from(tbody.rows) | 將即時的 HTMLCollection 轉為靜態陣列,避免排序時 DOM 變動造成索引錯亂 |
dataset.type | 在 <th> 上標記資料型別,排序邏輯據此分支 |
localeCompare('zh-Hant') | 正確處理繁體中文排序(注音/筆畫順序) |
tbody.appendChild(row) | 移動現有節點而非重建,效能佳且保留事件綁定 |
aria-sort="ascending|descending|none" 標示排序狀態<thead> 多列,需正確計算 colIndex 對應實際資料欄colspan/rowspan)會導致 cells 索引錯位,需額外處理trim() 去除空白,否則 " 100" 會被視為字串排在 "20" 前面