我已经搜索并努力实现这一点,但完全陷入困境,并希望有人在这里可以提供帮助。基本上我希望能够单击一个按钮并使用jQuery按组标题按字母顺序对无序列表进行排序,然后按字母顺序在每个组中对每个嵌套列表进行排序。非常感谢提前,这里... ...
默认列表:
<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>
单击按钮,然后将列表排序为以下内容:
<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 -->
答案 0 :(得分:1)
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>");
}
答案 1 :(得分:0)
我稍微修改了你的HTML,以便在这个答案中简化选择:
<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>
<ul id="newone">
<li class="grouphead">Fruit and Vegetables</li>
<ul id="Fruit">
</ul>
<li class="grouphead">Meat</li>
<ul id="Meat">
</ul>
</ul>
var dict = {
"Meat" : [],
"Fruit and Vegetables" : []
}
$("#list li").each( function() {
dict[$(this).children(":first").attr('rel')].push( $(this).html() );
} );
$.each( dict["Meat"], function(k, v) {
$("#Meat").append( "<li>" + v + "</li>" );
});
$.each( dict["Fruit and Vegetables"], function(k, v) {
$("#Fruit").append( "<li>" + v + "</li>" );
});