在jQuery中按字母顺序排序

时间:2015-01-05 08:21:46

标签: jquery sorting

编写工作代码,按字母顺序对列表进行排序。但代码很大而且不普遍。我想减少它。您能否告诉我们如何使代码更具通用性,因此您不必每次都添加新的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');

1 个答案:

答案 0 :(得分:1)

您可以使用$.each

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

并在sortUL

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