How may I sort a list alphabetically using jQuery?

后端 未结 10 2337
灰色年华
灰色年华 2020-11-21 23:13

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 alphabeti

10条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-21 23:33

    If you are using jQuery you can do this:

    $(function() {
    
      var $list = $("#list");
    
      $list.children().detach().sort(function(a, b) {
        return $(a).text().localeCompare($(b).text());
      }).appendTo($list);
    
    });
    
    
    
    • delta
    • cat
    • alpha
    • cat
    • beta
    • gamma
    • gamma
    • alpha
    • cat
    • delta
    • bat
    • cat

    Note that returning 1 and -1 (or 0 and 1) from the compare function is absolutely wrong.

提交回复
热议问题