當表格數值經過千分位格式化(例如加上逗號 1,000)後,jQuery tablesorter 往往會把逗號一起算進去,導致排序結果出錯。解法其實很簡單,只要找到取值的那個函式,把逗號過濾掉即可。
找到這個函式:
function getElementText(config, node) { var text = ""; if (!node) return ""; if (!config.supportsTextContent) config.supportsTextContent = node.textContent || false; if (config.textExtraction == "simple") { if (config.supportsTextContent) { text = node.textContent; } else { if (node.childNodes[0] && node.childNodes[0].hasChildNodes()) { text = node.childNodes[0].innerHTML; } else { text = node.innerHTML; } } } else { if (typeof(config.textExtraction) == "function") { text = config.textExtraction(node); } else { text = $(node).text(); } } return text; }
把它改成下面這樣即可:
function getElementText(config, node) { var text = ""; if (!node) return ""; if (!config.supportsTextContent) config.supportsTextContent = node.textContent || false; if (config.textExtraction == "simple") { if (config.supportsTextContent) { text = node.textContent; } else { if (node.childNodes[0] && node.childNodes[0].hasChildNodes()) { text = node.childNodes[0].innerHTML; } else { text = node.innerHTML; } } } else { if (typeof(config.textExtraction) == "function") { text = config.textExtraction(node); } else { text = $(node).text(); } } return (text.replace(/,/g,'')); }
差異只在最後一行:把原本直接回傳 text,改成先透過 text.replace(/,/g,'') 去除所有逗號再回傳。這樣 tablesorter 在比對數值時就不會被千分位符號干擾,排序自然恢復正確。以上就是修復這個 bug 的方法,希望對你有幫助。