按字母顺序排序 jQuery

Sort alphabetically in jQuery

编写工作代码,按字母顺序对列表进行排序。但是代码量大,不通用。我想减少它。你能告诉我如何使代码更通用,这样你就不必每次都添加一个新的 id 而不是每次都对 id 进行排序。

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);
}

<!-- Below is the code that needs to be reduced -->
$('.mg-filter-item:nth-child(1)').attr( 'id', 'id-1' );
$('.mg-filter-item:nth-child(2)').attr( 'id', 'id-2' );
$('.mg-filter-item:nth-child(3)').attr( 'id', 'id-3' );
$('.mg-filter-item:nth-child(4)').attr( 'id', 'id-4' );
$('.mg-filter-item:nth-child(5)').attr( 'id', 'id-5' );
$('.mg-filter-item:nth-child(6)').attr( 'id', 'id-6' );
$('.mg-filter-item:nth-child(7)').attr( 'id', 'id-7' );
$('.mg-filter-item:nth-child(8)').attr( 'id', 'id-8' );
$('.mg-filter-item:nth-child(9)').attr( 'id', 'id-9' );
$('.mg-filter-item:nth-child(10)').attr( 'id', 'id-10' );


sortUL('#id-1 ul');
sortUL('#id-2 ul');
sortUL('#id-3 ul');
sortUL('#id-4 ul');
sortUL('#id-5 ul');
sortUL('#id-6 ul');
sortUL('#id-7 ul');
sortUL('#id-8 ul');
sortUL('#id-9 ul');
sortUL('#id-10 ul');

你可以使用 $.each

$.each($('.mg-filter-item ul'), function() {
    sortUL($(this));
});

并且在sortUL

function sortUL(element) {
    element.children("li")./* ... */
}