What is the most efficient way to sort an Html Sel

2019-01-04 23:38发布

I have jQuery but I'm not sure if it has any built-in sorting helpers. I could make a 2d array of each item's text, value, and selected properties, but I don't think that javascript's built in Array.sort() would work correctly.

9条回答
家丑人穷心不美
2楼-- · 2019-01-05 00:27

Modified Tom's answer above slightly so that it actually modifies the contents of the select box to be sorted, rather than just returning the sorted elements.

$('#your_select_box').sort_select_box();

jQuery function:

$.fn.sort_select_box = function(){
    // Get options from select box
    var my_options = $("#" + this.attr('id') + ' option');
    // sort alphabetically
    my_options.sort(function(a,b) {
        if (a.text > b.text) return 1;
        else if (a.text < b.text) return -1;
        else return 0
    })
   //replace with sorted my_options;
   $(this).empty().append( my_options );

   // clearing any selections
   $("#"+this.attr('id')+" option").attr('selected', false);
}
查看更多
啃猪蹄的小仙女
3楼-- · 2019-01-05 00:27

There's a closed jQuery ticket for a sort that should work, but just wasn't included in the core.

jQuery.fn.sort = function() {
  return this.pushStack( [].sort.apply( this, arguments ), []);
};

Referenced from a Google Groups thread, I think you just pass in a function that is used to sort, like so

function sortSelect(selectToSort) {
    jQuery(selectToSort.options).sort(function(a,b){ 
        return a.value > b.value ? 1 : -1; 
    });
}

Hope it helps!

查看更多
We Are One
4楼-- · 2019-01-05 00:29

This is a better solution. Declare a global function to JQuery

$.fn.sortSelect = function() {
    var op = this.children("option");
    op.sort(function(a, b) {
        return a.text > b.text ? 1 : -1;
    })
    return this.empty().append(op);
}

And call the function from the code.

$("#my_select").sortSelect();
查看更多
登录 后发表回答