默认的自然排序将内容分成块进行比较,但这些块是由文本字符和数字的“块”设置的。当遇到非文本/数字字符时,它不会被分解。
因此,在您的演示中,值“#Elephant”和“0Zebra”排序将这些值分解如下:
#Elephant => [ '#Elephant' ]
0Zebra => [ '0', 'Zebra' ]
当比较完成时,它看到“#Elephant”不是数字,但“0”是数字,因此基于ascii comparison,非数字(假定为字母字符)值大于数字值;因此“#Elephant”排在“0Zebra”之后。
我知道您没有要求解释,但解决此问题的最简单方法是更换分拣机。请改用简单的文本排序器 (demo):
$('table').tablesorter({
textSorter: {
2: $.tablesorter.sortText
}
});
更新:如果您想要特定的排序,您需要重新排序 ascii 值。我设置了特定于数据的this demo,它只更改第一个字符。
var reorderAscii = function(x){
if (x === '') { return x; }
var v = x.charCodeAt(0),
z = x.charCodeAt(0);
if ( z > 90 && z < 97) {
// move [\]^_` to replace ABCDEF
v = v - 26;
} else if (z > 122 && z < 127) {
// move {|}~ to replace GHIJ
v = v - 52;
} else if (z > 47 && z < 58) {
// move 0123456789 to replace KLMNOPQRST
v = v + 27;
}
return z !== v ? String.fromCharCode(v) + x.slice(1) : x;
};
$('table').tablesorter({
theme: 'jui',
headerTemplate: '{content}{icon}',
// ignoreCase must = true
ignoreCase: true,
textExtraction: function(node, table, cellIndex){
var t = $.trim( $(node).text().toLowerCase() );
return cellIndex === 2 ? reorderAscii(t) : t;
},
textSorter: function (a, b) {
if (a == b) { return 0; }
if (a == '') { return 1; }
if (b == '') { return -1; }
return a > b ? 1 : -1;
},
widgets: ['uitheme', 'zebra', 'columns'],
widgetOptions: {
zebra: [
"ui-widget-content even",
"ui-state-default odd"]
}
});
我忘了提到使用除字母数字排序器之外的任何其他排序器,空单元格和字符串单元格排序将被忽略。我需要将其包含在文档中。