我的列表元素与此类似:
<ul id="alpha-list">
<li>Angel</li>
<li>Ball</li>
<li>Cat</li>
<li>Bat</li>
<li>Dog</li>
<li>Apple</li>
</ul>
我设法使用(返回a - b)函数按字母顺序对此列表项进行排序。
但是我希望将每个列表元素包装在父“ul li”中,以便最终结果看起来与此类似:
<ul id="alpha-list">
<li data-alphabet="A">
<ul>
<li>Angel</li>
<li>Apple</li>
</ul>
</li>
<li data-alphabet="B">
<ul>
<li>Ball</li>
<li>Bat</li>
</ul>
</li>
.....
</ul>
如何在此&amp;中找到独特的字母表然后将它们包装在新元素中?
答案 0 :(得分:2)
尝试
jQuery(function () {
//First create a list of objects containing the unique set of characters and the correspondign li elements
var map = {}, list = [];
$('#alpha-list li').each(function () {
var char = $.trim($(this).text())[0];
var array = map[char];
if (!array) {
array = [];
map[char] = array;
list.push({
char: char,
array: array
})
}
array.push(this);
});
//sort the list alphabetically
list.sort(function (obj1, obj2) {
return obj1.char.localeCompare(obj2.char)
});
//then create the new structure
$.each(list, function (_, item) {
var $li = $('<li />', {
'data-alphabet': item.char
}).appendTo('#alpha-list');
var $ul = $('<ul />').append(item.array).appendTo($li);
})
})
演示:Fiddle
答案 1 :(得分:0)
这是你想要的。
$('#alpha-list').find('li').sort(function (a, b) {
a = $(a).text();
b = $(b).text();
if (a < b) {
return -1
} else if (a > b) {
return 1;
} else {
return 0;
}
}).each(function (idx, e) {
var val = $(e).text();
var wrap = $('#alpha-list').find('[data-alphabet="' + val.charAt(0).toUpperCase() + '"]');
if (wrap.length == 0) {
console.log('create');
$('#alpha-list').append('<ul data-alphabet="' + val.charAt(0).toUpperCase() + '">' + e.outerHTML + '</ul>');
} else {
console.log('append');
wrap.append($(e))
}
})
答案 2 :(得分:0)
我是这样做的。例如:http://jsbin.com/IwOZiPas/1
var items = [];
ordered_list = "";
$('#alpha-list li').each(function(){
items.push($(this).html());
});
items.sort();
current_letter="";
for(var i = 0, l = items.length; i < l; i++)
{
if(items[i].substr(0,1).toUpperCase() != current_letter){
ordered_list +="</ul><li data-alphabet='"+items[i].substr(0,1).toUpperCase()+"'>"+items[i].substr(0,1).toUpperCase() +"</li><ul></li><li>"+items[i]+"</li>";
current_letter = items[i].substr(0,1).toUpperCase() ;
}
else
ordered_list +="<li>"+items[i]+"</li>";
}
$('#alpha-list').html(ordered_list);