订购< UL>/< OL>的最简单方法是什么?在jQuery中?
问题描述:
我正在寻找一些示例代码,这些代码将按字母顺序对HTML列表中的列表项进行排序.有人可以帮忙吗?
I'm looking for some sample code that will sort the list items in an HTML list by alphabetical order. Can anyone help?
以下是供人们使用的示例列表:
Here is a sample list for people to work with:
<ul class="alphaList">
<li>apples</li>
<li>cats</li>
<li>bears</li>
</ul>
答
var items = $('.alphaList > li').get();
items.sort(function(a,b){
var keyA = $(a).text();
var keyB = $(b).text();
if (keyA < keyB) return -1;
if (keyA > keyB) return 1;
return 0;
});
var ul = $('.alphaList');
$.each(items, function(i, li){
ul.append(li); /* This removes li from the old spot and moves it */
});