Sorting Select box with jQuery

后端 未结 5 1827
情话喂你
情话喂你 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 11:15

    You can use the .attr() function to get the value of an attribute in jQuery. See http://api.jquery.com/attr/ for more info.

    Try this:

    $(object).each(function() {
    
        // Keep track of the selected option.
       var selectedValue = $(this).val();
    
       // sort it out
       $(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 
       }));
    
       // Select one option.
       $(this).val(selectedValue);
    
    });
    

提交回复
热议问题