【问题标题】:Jquery, sorting & grouping for alphanumeric valuesJquery,字母数字值的排序和分组
【发布时间】: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


    【解决方案1】:

    问题是isNaN 在您提供字符串时需要一个数字。 此外,您没有处理x 是数字而y 是字符串的情况,反之亦然。

    你应该使用这个比较器:

    function compare(x, y) {
        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;
            }
        }
    }
    

    【讨论】:

    • 经过大量调试后才发现它仍然没有对数字进行排序,因为它们带有''(以字符串的形式):|有什么帮助吗?
    • 根据您的建议和我发现的问题,我正在编辑更新代码的问题。
    • 你能举一个例子(例如 jsfiddle 或类似的东西)它不起作用吗?
    猜你喜欢
    • 1970-01-01
    • 2018-04-18
    • 1970-01-01
    • 2021-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多