What is the easiest way to order a
    /
      in jQ

2019-01-01 13:34发布

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>

3条回答
余欢
2楼-- · 2019-01-01 13:34

Try this:

var elems = $('.alphalist li').detach().sort(function (a, b) {
  return ($(a).text() < $(b).text() ? -1 
        : $(a).text() > $(b).text() ? 1 : 0);
}); 
$('.alphalist').append(elems);
查看更多
梦寄多情
3楼-- · 2019-01-01 13:35

For future googlers, I've found this plugin very useful. It has option to define character order for non-latin languages.

Older versions (jQuery dependent)

$('.submenu > li').tsort({
    charOrder: 'abcçdefgğhıijklmnoöprsştuüvyz'
});

For English only characters, no option is needed to define

$('.submenu > li').tsort();

Current version (jQuery independent) (29 March 2016)

Current version of tinysort is now independent from jQuery. Pure JavaScript. I updated jsfiddle for new version usage.

tinysort('.submenu > li', {
    charOrder: 'abcçdefgğhıijklmnoöprsştuüvyz'
});

Demo http://jsfiddle.net/ergec/EkScy/

Website http://tinysort.sjeiti.com/

查看更多
妖精总统
4楼-- · 2019-01-01 13:47
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 */
});
查看更多
登录 后发表回答