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.
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.
将选项提取到临时数组中,排序,然后重建列表:
var my_options = $("#my_select option");
var selected = $("#my_select").val();
my_options.sort(function(a,b) {
if (a.text > b.text) return 1;
if (a.text < b.text) return -1;
return 0
})
$("#my_select").empty().append( my_options );
$("#my_select").val(selected);
Mozilla's sort documentation (specifically the compareFunction) and Wikipedia's Sorting 算法rithm page are relevant.
If you want to make the sort case insensitive, replace text
with text.toLowerCase()
上面显示的排序函数说明了如何排序.准确地对非英语语言进行排序可能很复杂(请参见unicode collation algorithm).在排序函数中使用localeCompare是一个很好的解决方案,例如:
my_options.sort(function(a,b) {
return a.text.localeCompare(b.text);
});