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

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

现场演示→

Live Demo →

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

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