How may I sort a list alphabetically using jQuery?

后端 未结 10 2130
灰色年华
灰色年华 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:32

    @SolutionYogi's answer works like a charm, but it seems that using $.each is less straightforward and efficient than directly appending listitems :

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

    Fiddle

提交回复
热议问题