开发者

Ordering returned elements from a .each() call using a .data()

I have a html list with various values attached to each <li>.

Can I order the elements based on an associated .data() value?

This is so I 开发者_运维技巧can create a summary panel with entries sorted by .data('DataValueX').

Just to clarify I don't need to sort the original elements just use data from them to create a new summary panel.


JavaScript has a native method called .sort(sort_function) that you can use to sort any array. In this case, you have a jQuery object collection which has an array stack of elements.

Check my fiddle for a demo of it in action.

$(function() {
    var myArray = $('li').get();  

    myArray.sort(function(x,y) {
        return $(x).data('color') > $(y).data('color') ? 1 : -1;
    });

    $('ul').empty().append(myArray);
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜