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?
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:
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");
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.