这是另一种方法:
var compare = function(a, b) {
return a > b ? 1 : a === b ? 0 : -1;
},
compareAlphanumeric = function (a, b) {
alpha = compare(a.alpha, b.alpha);
numeric = compare(a.numeric, b.numeric);
return (alpha === 1 | (alpha === 0 && numeric === 1)) ? 1 : (alpha === 0 && numeric === 0) ? 0 : -1;
};
jQuery.fn.dataTableExt.oSort['alphaNumeric-asc'] = function(a, b) {
var r = /^([A-Za-z]+)([0-9]+$)/,
a = {
"alpha": a.split(r)[1],
"numeric": parseInt(a.split(r)[2], 10)
},
b = {
"alpha": b.split(r)[1],
"numeric": parseInt(b.split(r)[2], 10)
};
return compareAlphanumeric(a, b);
};
jQuery.fn.dataTableExt.oSort['alphaNumeric-desc'] = function(a, b) {
var r = /^([A-Za-z]+)([0-9]+$)/,
a = {
"alpha": a.split(r)[1],
"numeric": parseInt(a.split(r)[2], 10)
},
b = {
"alpha": b.split(r)[1],
"numeric": parseInt(b.split(r)[2], 10)
};
return compareAlphanumeric(b, a); //reverse a and b for desc
};
在这里工作小提琴:http: //jsfiddle.net/jEqu2/3/
该compare
函数是您的基本比较函数。compareAlphanumeric
根据以下真值表返回 1、0 或 -1:
/*
Alpha Numeric Result
-1 -1 -1
-1 0 -1
-1 1 -1
0 -1 -1
0 0 0
0 1 1
1 -1 1
1 0 1
1 1 1
*/
大部分实际工作是在oSort
函数中完成的:
//First declare a RegExp to split the location into an array of [letter, number]
var r = /^([A-Za-z]+)([0-9]+$)/,
//convert the passed "a" parameter to an object containing its letter and number,
//and parse the number portion to an actual number instead of its string representation.
a = {
"alpha": a.split(r)[1],
"numeric": parseInt(a.split(r)[2], 10)
},
//do the same for b
b = {
"alpha": b.split(r)[1],
"numeric": parseInt(b.split(r)[2], 10)
};
//return the alphanumeric comparison
return compareAlphanumeric(a, b);
而在降序oSort
中,我们只需要切换传递给的参数的顺序即可compareAlphanumeric
。