基于数据属性的排序列表(使用jquery元数据插件)

jyo*_*eph 8 sorting jquery metadata

我很难确定如何根据data属性中的一个键/值对来排序列表.

<ul>
    <li data="{name:'Foo', number: '1'}">
        <h3>Foo</h3>
    </li>

    <li data="{name:'Bar', number: '2'}">
        <h3>Bar</h3>
    </li>
</ul>
Run Code Online (Sandbox Code Playgroud)

这是jQuery.我正在设置元数据attr并访问它.所有这一切都很好.

jQuery.metadata.setType("attr", "data");

$(document).ready(function(){   

    // loop through each list item and get the metadata
    $('ul li').each(function () {  
        console.log($(this).metadata());
        // shows the following - Object {name="Foo", number="1"}
    });

)};
Run Code Online (Sandbox Code Playgroud)

示例:我需要按名称升序排序.有人能指出我正确的方向吗?

编辑:

这是我用来触发排序的表单:

<form name="filterForm">
    Sort: 
    <select name="sort" size="1">
        <option value="nameAsc" <cfif URL.sort EQ 1>selected="selected"</cfif>>Name A to Z</option>
        <option value="nameDesc" <cfif URL.sort EQ 2>selected="selected"</cfif>>Name Z to A</option>
        <option value="numberAsc" <cfif URL.sort EQ 3>selected="selected"</cfif>>Number 1-10</option>
        <option value="numberDesc" <cfif URL.sort EQ 4>selected="selected"</cfif>>Number 10-1</option>
    </select> 
</form> 
Run Code Online (Sandbox Code Playgroud)

以及处理更改事件的jquery,但我不确定我是否正确实现了Mikael Eliasson的代码,因为我不确定在哪里传递所选内容的值:

$('form[name=filterForm] select').change(function(){

    var sortBy = this.value;

    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(appendItems());

    function appendItems(){

        //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());
        }       

    }


});
Run Code Online (Sandbox Code Playgroud)

Mik*_*son 6

Javascript有一个sort函数,可以将函数作为参数.当您进行自定义比较时,应该使用此函数.请参见http://www.w3schools.com/jsref/jsref_sort.asp

所以我要做的就是这样的事情

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());
});
Run Code Online (Sandbox Code Playgroud)

编辑:上面.each循环的更新语法 - 修复语法错误

编辑:更正了最后一个循环中的错误

EDIT2:通过请求我正在使用比较功能进行更新

function compare(a, b){
   return a.name - b.name;
}
Run Code Online (Sandbox Code Playgroud)