如何使用 jQuery 按字母顺序对列表进行排序?

问题描述:

我对这里的理解有点超出我的理解,我希望这实际上是可能的.

I'm a bit out of my depth here and I'm hoping this is actually possible.

我希望能够调用一个函数来按字母顺序对列表中的所有项目进行排序.

I'd like to be able to call a function that would sort all the items in my list alphabetically.

我一直在浏览 jQuery UI 进行排序,但似乎不是这样.有什么想法吗?

I've been looking through the jQuery UI for sorting but that doesn't seem to be it. Any thoughts?

不需要需要 jQuery 来做到这一点...

You do not need jQuery to do this...

function sortUnorderedList(ul, sortDescending) {
  if(typeof ul == "string")
    ul = document.getElementById(ul);

  // Idiot-proof, remove if you want
  if(!ul) {
    alert("The UL object is null!");
    return;
  }

  // Get the list items and setup an array for sorting
  var lis = ul.getElementsByTagName("LI");
  var vals = [];

  // Populate the array
  for(var i = 0, l = lis.length; i < l; i++)
    vals.push(lis[i].innerHTML);

  // Sort it
  vals.sort();

  // Sometimes you gotta DESC
  if(sortDescending)
    vals.reverse();

  // Change the list on the page
  for(var i = 0, l = lis.length; i < l; i++)
    lis[i].innerHTML = vals[i];
}

易于使用...

sortUnorderedList("ID_OF_LIST");

现场演示 →