點擊表格表頭(th)即可對該欄資料進行升/降冪排序,支援數值、字串、日期等型別,股票行情、資料報表常見需求。
render() 重繪 tbody。Array.sort((a,b) => comparator(a[key], b[key]) * direction),direction 切換 1/-1。a - b,字串用 localeCompare,日期用 new Date(a) - new Date(b)。var data = [ {name:'A', price:100, date:'2023-01-01'}, ... ];
var sortKey = null, sortDir = 1;
function render() {
$('tbody').innerHTML = data.map(row => '<tr><td>' + row.name + '</td><td>' + row.price + '</td>...').join('');
// 更新表頭箭頭
document.querySelectorAll('th').forEach(th => {
th.classList.remove('asc','desc');
if (th.dataset.key === sortKey) th.classList.add(sortDir === 1 ? 'asc' : 'desc');
});
}
document.querySelectorAll('th[data-key]').forEach(th => {
th.style.cursor = 'pointer';
th.onclick = function() {
var key = this.dataset.key;
if (sortKey === key) sortDir *= -1; else { sortKey = key; sortDir = 1; }
data.sort((a,b) => compare(a[key], b[key]) * sortDir);
render();
};
});
function compare(a,b) {
if (!isNaN(a) && !isNaN(b)) return a - b;
var da = Date.parse(a), db = Date.parse(b);
if (!isNaN(da) && !isNaN(db)) return da - db;
return String(a).localeCompare(String(b));
}