使用jQuery将列表排序为带有标题的组 [英] Use jQuery to sort a list into groups with headings

查看:67
本文介绍了使用jQuery将列表排序为带有标题的组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索并努力实现这一点,但完全陷入困境,并希望有人在这里可以提供帮助。基本上我希望能够单击一个按钮并使用jQuery按组标题按字母顺序对无序列表进行排序,然后按字母顺序在每个组中对每个嵌套列表进行排序。非常感谢提前,这里... ...

I have searched and tried hard to achieve this but completely stuck and hoping somebody on here can help. Basically I would like to be able to click on a button and use jQuery to sort an unordered list alphabetically by group heading and then each nested list alphabetically within each group. Many thanks in advance and here goes...

默认列表:

<ul id="list">
 <li><a href="#" rel="Meat">Lamb</a></li>
 <li><a href="#" rel="Meat">Pork</a></li>
 <li><a href="#" rel="Meat">Beef</a></li>
 <li><a href="#" rel="Fruit and Vegetables">Banana</a></li>
 <li><a href="#" rel="Fruit and Vegetables">Orange</a></li>
 <li><a href="#" rel="Fruit and Vegetables">Cabbage</a></li>
</ul>

单击按钮然后将列表排序为以下内容:

Click a button and then sort the list to something like this:

<ul id="list">
 <li class="grouphead">Fruit and Vegetables</li>
  <ul>
   <li><a href="#" rel="Fruit and Vegetables">Banana</a></li>
   <li><a href="#" rel="Fruit and Vegetables">Cabbage</a></li>
   <li><a href="#" rel="Fruit and Vegetables">Orange</a></li>
  </ul>
 <li class="grouphead">Meat</li>
  <ul>
   <li><a href="#" rel="Meat">Beef</a></li>
   <li><a href="#" rel="Meat">Lamb</a></li>
   <li><a href="#" rel="Meat">Pork</a></li>
  </ul>
</ul><!-- End: #list -->


推荐答案

var dict = {
}

//read items from list
$("#list li").each( function() {
    var k = $(this).children(":first").attr('rel');
    if ( dict.hasOwnProperty(k) == false ) {
        dict[k] = [];
    }
    dict[k].push( $(this).html() );
} );

//clear old list items
$("#list").empty();

function newList(nam) {
    var r = "";
    for ( c in dict[nam] ) {
        r += "<li>" + dict[nam][c] + "</li>";
    }    
    return r;
}

//create new list
for ( nam in dict ) {
    $("#list").append("<li class='grouphead'>" + nam + "</li>");
    $("#list").append("<ul>" + newList(nam) + "</ul>");
}

http://jsfiddle.net/r5QQT/7/

这篇关于使用jQuery将列表排序为带有标题的组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆