使用jQuery将列表排序为带有标题的组
我已经搜索并努力实现这一点,但完全陷入困境,并希望有人在这里可以提供帮助。 基本上我希望能够单击一个按钮并使用jQuery按组标题按字母顺序对无序列表进行排序,然后在每个组中按字母顺序对每个嵌套列表进行排序。 非常感谢提前,这里…
默认列表:
单击一个按钮,然后将列表排序为以下内容:
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 += "" + dict[nam][c] + " "; } return r; } //create new list for ( nam in dict ) { $("#list").append("" + nam + " "); $("#list").append("" + newList(nam) + "
"); }
我在这个答案中修改了你的HTML,使选择更简单:
- Fruit and Vegetables
Meat
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( "" + v + " " ); }); $.each( dict["Fruit and Vegetables"], function(k, v) { $("#Fruit").append( "" + v + " " ); });
这是一个小提琴: http : //jsfiddle.net/r5QQT/1/