我有一个这样的清单:
<ul id="recipes">
<li><a href='xxx'>Apple Pie</a></li>
<li><a href='xxx'>Almond Slice</a></li>
<li><a href='xxx'>Banana Cake</a></li>
<li><a href='xxx'>Carrot Cake</a></li>
</ul>
我需要转换为按字母顺序分组的列表:
<h3>A<h3>
<ul>
<li><a href='xxx'>Apple Pie</a></li>
<li><a href='xxx'>Almond Slice</a></li>
</ul>
<h3>B<h3>
<ul>
<li><a href='xxx'>Banana Cake</a></li>
</ul>
<h3>C<h3>
<ul>
<li><a href=''xxx'>Carrot Cake</a></li>
</ul>
我已经用jQuery对列表进行了排序,但是无法弄清楚如何实现我需要的分组,有人可以帮忙吗?
编辑:我可以在原始列表中添加更多信息,所以看起来像这样:
<ul id="recipes">
<li class='a'><a href='xxx'>Apple Pie</a></li>
<li class='a'><a href='xxx'>Almond Slice</a></li>
<li class='b'><a href='xxx'>Banana Cake</a></li>
<li class='c'><a href='xxx'>Carrot Cake</a></li>
</ul>
我怀疑这会有很大帮助
答案 0 :(得分:2)
这样的事情怎么样?
var headings = 'abcdefghijklmnopqrstuvwxyz';
var $recipes = $('#recipes').detach();
$.each(headings, function(){
$('body').append('<h3>' + this + '</h3>');
$('body').append($('<ul/>').append($recipes.find('.' + this)));
});
示例jsfiddle
答案 1 :(得分:0)
我发现另一个解决方案类似的解决方案:
var letters = [ "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z" ];
$.each(letters, function(idx,val) {
$("li." + val).wrapAll("<div><h3>" + val.toUpperCase() + "</h3><ul></ul></div>");
});