订购<UL>/<OL>的最简单方法是什么?在 jQuery 中?

订购<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 */
});