The following code rearranges elements by the attribute "amount". How can I alter this code so the items will be reversed? Thanks.
var parent = $('#items');
var children = $('a', parent);
children.sort(function(a, b) {
开发者_Go百科 return parseInt($(a).attr('amount')) - parseInt($(b).attr('amount'));
})
$.each(children, function(i, child) {
parent.append(child);
});
Change the order of the values you are comparing (b-a
instead of a-b
):
var children = $('a', parent).sort(function(a, b) {
return parseInt($(b).attr('amount'), 10) - parseInt($(a).attr('amount'), 10);
});
Use prepend instead of append?
http://docs.jquery.com/Manipulation/prepend#content
I've used this technique. It's ideal for small collections.
jQuery.fn.reverse = function() {
return this.pushStack(this.get().reverse(), arguments);
};
var r = $('.class').reverse();
children.sort(function(a, b) {
return parseInt($(a).attr('amount')) < parseInt($(b).attr('amount')) ? 0 : 1;
});
精彩评论