Sorting Select box with jQuery

后端 未结 5 1944
情话喂你
情话喂你 2021-01-04 10:20

I have a select box on a form, which carries an incremental rel attribute. I have a function that can sort the options by thier .text() value, into alphabetcal order.

<
5条回答
  •  孤独总比滥情好
    2021-01-04 10:58

    If you want to sort by rel you should change your function

    $(this).html($("option", $(this)).sort(function(a, b) { 
        var arel = $(a).attr('rel');
        var brel = $(b).attr('rel');
        return arel == brel ? 0 : arel < brel ? -1 : 1 
    }));
    

    edit with parseInt()

    $(this).html($("option", $(this)).sort(function(a, b) { 
        var arel = parseInt($(a).attr('rel'), 10);
        var brel = parseInt($(b).attr('rel'), 10);
        return arel == brel ? 0 : arel < brel ? -1 : 1 
    }));
    

提交回复
热议问题