Alphabetize a list using JS or jQuery

后端 未结 5 999
孤独总比滥情好
孤独总比滥情好 2020-12-18 16:32

I\'m trying to take the contents of a list, that is not in alphabetical order, then by adding each item to an array, sort them into alphabetical order and insert them back i

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-18 17:11

    There's no need to generate an array here, you can use the sort() method directly on the jQuery object resulting from selecting the li elements. After sorting you can then append them back to the parent ul in the corrected order. Try this:

    $("li").sort(function(a, b) {
        var aText = $(a).text(), bText = $(b).text();
        return aText < bText ? -1 : aText > bText ? 1 : 0;
    }).appendTo('ul');
    

    Updated fiddle

    Also note that having duplicate id attributes in a document is invalid. Your #alphabet elements should be changed to use a class instead.

提交回复
热议问题