简体   繁体   English

使用jQuery对li进行排序

[英]Using jQuery to sort li

I have this script that I use to sort a list of li 's, however it is not working when there is more than one digit, it is sorting with the first digit taking preference, so 10 comes before 2. Is there a way to modify this so it sorts it based on the numeric value? 我有一个用于对li的列表进行排序的脚本,但是当有多个数字时,它不起作用,它优先选择第一个数字,因此10在2之前。有没有办法修改它,以便根据数值对它进行排序?

jQuery.fn.sortDomElements = (function() {
    return function(comparator) {
        return Array.prototype.sort.call(this, comparator).each(function(i) {
              this.parentNode.appendChild(this);
        });
    };
})();

$("#sortable3, #sortable4").children().sortDomElements(function(a,b){
    akey = $(a).attr("sortkey");
    bkey = $(b).attr("sortkey");
    if (akey == bkey) return 0;
    if (akey < bkey) return -1;
    if (akey > bkey) return 1;
});

You're comparing strings. 您正在比较字符串。 When comparing strings you get this: 比较字符串时,您得到以下信息:

"10" <  "2"
true

Instead force the string to ints base 10: 而是将字符串强制为以10为底的整数:

parseInt("10", 10) <  parseInt("1", 10)
false

Trying this: 试试这个:

$("#sortable3, #sortable4").children().sortDomElements(function(a,b){
    akey = parseInt(($(a).attr("sortkey"), 10);
    bkey = parseInt($(b).attr("sortkey"), 10);
    if (akey == bkey) return 0;
    if (akey < bkey) return -1;
    if (akey > bkey) return 1;
});

should fix it. 应该修复它。

Try converting the key to a number. 尝试将密钥转换为数字。

akey = parseInt($(a).attr("sortkey");
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM