How may I sort a list alphabetically using jQuery?

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

    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/

    Above code will sort your unordered list with id 'myUL'.

    OR you can use a plugin like TinySort. https://github.com/Sjeiti/TinySort

提交回复
热议问题