javascript - Jquery incorrectly sort <li> by id -
i have <li>
sort id:
<ul id="members-list"> <li id="member_8"> <li id="member_4"> <li id="member_7"> <li id="member_12"> <li id="member_11"> <li id="member_13"> <li id="member_5"> <li id="member_6"> <li id="member_9"> <li id="member_3"> <li id="member_2"> <li id="member_1"> <li id="member_10"> </ul>
the code use:
<script> $( document ).ready(function() { $("li[id*='member_']").sort(function (a, b) { return parseint(a.id.replace('member_', '')) > parseint(b.id.replace('member_', '')); }).each(function () { var elem = $(this); elem.remove(); $(elem).appendto("ul#members-list"); }); }); </script>
the result is:
<ul id="members-list"> <li id="member_5"> <li id="member_8"> <li id="member_7"> <li id="member_1"> <li id="member_2"> <li id="member_3"> <li id="member_4"> <li id="member_6"> <li id="member_9"> <li id="member_10"> <li id="member_11"> <li id="member_12"> <li id="member_13"> </ul>
the <li>
no not sorted correctly, can cause problem?
the problem did not implement sort
function correctly. function supposed return positive number, negative number or zero; you're returning true/false.
so when a.id less than/equal b.id function returns false zero-ish; treated a.id equal b.id; puts sorting function off track.
solution change this:
return parseint(a.id.replace('member_', '')) > parseint(b.id.replace('member_', ''));
to this:
return parseint(a.id.replace('member_', '')) - parseint(b.id.replace('member_', ''));
having said that, rewrite code using detach
, single appendto
this:
$("li[id*='member_']").detach().sort(function(a, b) { return +a.id.replace("member_", "") - b.id.replace("member_", ""); }).appendto("ul#members-list");
Comments
Post a Comment