報表型頁面經常需要讓使用者點一下欄位標題就排序。這個功能看似複雜,拆開來其實是「取出資料列 → 依型別比較 → 重新組回表格」三個步驟。本文示範支援數字、日期與字串三種排序型別的通用寫法。
要排序的資料列必須放在 <tbody> 之中,這樣才能用 outerHTML 精準切出「表頭 + 資料 + 表尾」三段,排序後再拼回去,不必逐一搬動 DOM 節點。
var isDescending = true;
/**
* tableId 表格 ID
* colNo 排序的列號,從 0 開始
* startRowNo 開始排序的列號,從 0 開始
* sortLength 要排序的資料列數
* type 排序型別:NUMBER / DATE / STRING
*/
function sort(tableId, colNo, startRowNo, sortLength, type) {
if (sortLength <= 1) return;
var currTable = document.getElementById(tableId);
var html = currTable.outerHTML;
var theHeader = html.substring(0, html.toUpperCase().indexOf('<TBODY>') + 7);
var theFooter = html.substring(html.toUpperCase().indexOf('</TBODY>') - 8);
var theRows = new Array(sortLength);
for (var i = startRowNo; i < sortLength + startRowNo; i++) {
var text = currTable.rows[i].cells[colNo].innerText.toLowerCase();
theRows[i - startRowNo] = [text, currTable.rows[i].outerHTML];
}
var t = type.toUpperCase();
if (t == 'NUMBER') theRows.sort(compareNumber);
else if (t == 'DATE') theRows.sort(compareDate);
else theRows.sort(compareString);
var tableInfo = "";
for (var j = 0; j < theRows.length; j++) tableInfo += theRows[j][1];
isDescending = !isDescending;
currTable.outerHTML = theHeader + tableInfo + theFooter;
}
數字:先去掉千分位逗號再轉浮點,並把空白視為 0,避免 NaN 導致排序失效。
function compareNumber(x, y) {
var a = x[0].excludeChars(",").trim(), b = y[0].excludeChars(",").trim();
if (a == "") a = 0;
if (b == "") b = 0;
return isDescending ? parseFloat(b) - parseFloat(a)
: parseFloat(a) - parseFloat(b);
}
字串:直接比較大小即可。
function compareString(x, y) {
if (isDescending) {
if (x[0] > y[0]) return -1;
if (x[0] < y[0]) return 1;
return 0;
}
if (x[0] < y[0]) return -1;
if (x[0] > y[0]) return 1;
return 0;
}
日期:以「-」拆成年月日,轉成時間戳相減。
function compareDate(x, y) {
var a = x[0].split("-"), b = y[0].split("-");
var t1 = new Date(a[0], a[1], a[2]).getTime();
var t2 = new Date(b[0], b[1], b[2]).getTime();
return isDescending ? t2 - t1 : t1 - t2;
}
輔助用的去除字元函式掛在 String 上:
String.prototype.excludeChars = function(chars){
return this.replace(new RegExp(chars, "g"), '');
};
直接用 outerHTML 字串重組表格的做法在十年前很常見,但今天有更好的選擇:把資料存在 JavaScript 陣列裡排序,再用 documentFragment 一次插入,或者直接 template 重繪 tbody。這樣不必解析 HTML 字串,也能保留原本的 event listener。此外 localeCompare() 對中文排序的支援遠優於直接用 > 運算子,處理中文欄位時值得改用。