Sort list based on data attribute (using jquery metadata plugin)

微笑、不失礼 提交于 2019-12-05 04:14:06
Mikael Eliasson

Javascript has a sort function which can take a function as argument. This function is supposed to be used when you have custom comparisons. See http://www.w3schools.com/jsref/jsref_sort.asp

So what I would do is somethings like this

var arr = []
// loop through each list item and get the metadata
    $('ul li').each(function () {  
        var meta = $(this).metadata();
        meta.elem = $(this);
        arr.push(meta);
    });
 arr.sort(compare);

//Foreach item append it to the container. The first i arr will then end up in the top
$.each(arr, function(index, item){
    item.elem.appendTo(item.elem.parent());
});

EDIT: Updated syntax on above .each loop - fixing syntax error

EDIT: Corrected a error in the last each loop

EDIT2: By request I'm updating with the compare function

function compare(a, b){
   return a.name - b.name;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!