如何使用 jQuery 按字母顺序对列表进行排序? [英] How may I sort a list alphabetically using jQuery?

查看:40
本文介绍了如何使用 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");

现场演示 →

这篇关于如何使用 jQuery 按字母顺序对列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆