Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
487 views
in Technique[技术] by (71.8m points)

javascript - 如何使用jQuery按字母顺序对列表进行排序?(How may I sort a list alphabetically using 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.(我希望能够调用一个函数,该函数将按字母顺序对列表中的所有项目进行排序。)

I've been looking through the jQuery UI for sorting but that doesn't seem to be it.(我一直在寻找通过jQuery UI进行排序,但事实并非如此。)

Any thoughts?(有什么想法吗?)   ask by translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Something like this:(像这样:)

var mylist = $('#myUL');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
   return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });

From this page: http://www.onemoretake.com/2009/02/25/sorting-elements-with-jquery/(在此页面上: http : //www.onemoretake.com/2009/02/25/sorting-elements-with-jquery/)

Above code will sort your unordered list with id 'myUL'.(上面的代码将对ID为“ myUL”的无序列表进行排序。)

OR you can use a plugin like TinySort.(或者,您可以使用TinySort之类的插件。)

https://github.com/Sjeiti/TinySort(https://github.com/Sjeiti/TinySort)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...