How may I sort a list alphabetically using jQuery?

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

    Put the list in an array, use JavaScript's .sort(), which is by default alphabetical, then convert the array back to a list.

    http://www.w3schools.com/jsref/jsref_sort.asp

    0 讨论(0)
  • 2020-11-21 23:52

    To make this work work with all browsers including Chrome you need to make the callback function of sort() return -1,0 or 1.

    see http://inderpreetsingh.com/2010/12/01/chromes-javascript-sort-array-function-is-different-yet-proper/

    function sortUL(selector) {
        $(selector).children("li").sort(function(a, b) {
            var upA = $(a).text().toUpperCase();
            var upB = $(b).text().toUpperCase();
            return (upA < upB) ? -1 : (upA > upB) ? 1 : 0;
        }).appendTo(selector);
    }
    sortUL("ul.mylist");
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-21 23:54

    improvement based on Jeetendra Chauhan's answer

    $('ul.menu').each(function(){
        $(this).children('li').sort((a,b)=>a.innerText.localeCompare(b.innerText)).appendTo(this);
    });
    

    why i consider it an improvement:

    1. using each to support running on more than one ul

    2. using children('li') instead of ('ul li') is important because we only want to process direct children and not descendants

    3. using the arrow function (a,b)=> just looks better (IE not supported)

    4. using vanilla innerText instead of $(a).text() for speed improvement

    5. using vanilla localeCompare improves speed in case of equal elements (rare in real life usage)

    6. using appendTo(this) instead of using another selector will make sure that even if the selector catches more than one ul still nothing breaks

    0 讨论(0)
提交回复
热议问题