How may I sort a list alphabetically using jQuery?

后端 未结 10 2185
灰色年华
灰色年华 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: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");
    

提交回复
热议问题