代码之家  ›  专栏  ›  技术社区  ›  jyoseph

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

  •  8
  • jyoseph  · 技术社区  · 14 年前

    我很难弄清楚如何根据数据属性中的一个键/值对对对列表进行排序。

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

    这是jquery。我正在设置元数据属性并访问它。所有这些都可以。

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

    示例:我需要按名称升序排序。有人能给我指个方向吗?

    编辑:

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

    <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> 
    

    以及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());
            }       
    
        }
    
    
    });
    
    1 回复  |  直到 12 年前
        1
  •  6
  •   Mark Willis    12 年前

    javascript有一个排序函数,它可以将一个函数作为参数。当您进行自定义比较时,应该使用此函数。见 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());
    });
    

    编辑:更新了上面的语法。每个循环-修复语法错误

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

    edit2:根据请求,我正在用比较函数更新

    function compare(a, b){
       return a.name - b.name;
    }