开发者

Reversing order of elements

开发者 https://www.devze.com 2022-12-11 05:40 出处:网络
The following code rearranges elements by the attribute \"amount\". How can I alter this code so the items will be reversed? Thanks.

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;
});
0

精彩评论

暂无评论...
验证码 换一张
取 消