【发布时间】:2014-03-25 08:37:48
【问题描述】:
我有一个项目列表,其中包含字母和数字两种类型的值。 我需要像按字母排序然后按数字排序一样对它们进行排序。例如:Apple Car 23 45 我可以使用以下方法对它们进行排序:
$(function() {
$.fn.sortList = function() {
debugger;
var mylist = $(this);
var listitems = $('a', mylist).get();
listitems.sort(function(x, y) {
if (isNaN(x.text) && isNaN(y.text)) {
var compA = $(x).text().toUpperCase();
var compB = $(y).text().toUpperCase();
return (compA < compB) ? -1 : 1;
} else {
return (x.text < y.text) ? -1 : 1;}
}
);
$.each(listitems, function(i, itm) {
mylist.append(itm);
});
}
});
//Call this function to sort the list
$("div#countries").sortList();
但是使用这个,数字有时会排在首位,有时会排在首位(不知道为什么),并且字母排在数字之后。 我尝试搜索许多论坛进行完全排序和分组,但在 jquery 中我无法做到这一点。(我想念 C# LinQ):|请帮忙。
编辑 1:
根据以下建议,我正在使用此代码,但我的数值也以字符串的形式出现,这就是数字没有被整理出来的原因。
代码:
$(function() {
$.fn.sortList = function() {
debugger;
var mylist = $(this);
var listitems = $('a', mylist).get();
listitems.sort(function(x, y) {
if($.isNumeric(x.text)){
x.text = parseInt(x.text);
}
if($.isNumeric(y.text)){
y.text = parseInt(y.text);
}
var a = Number(x.text);
var b = Number(y.text);
if (isNaN(a)) {
if (isNaN(b)) {
var compA = x.text.toUpperCase();
var compB = y.text.toUpperCase();
return (compA < compB) ? -1 : 1;
} else {
return -1;
}
}
else{
if (isNaN(b)) {
return 1;
} else {
return a - b;
}
}
});
$.each(listitems, function(i, itm) {
mylist.append(itm);
});
}
});
【问题讨论】:
标签: javascript jquery sorting