问题描述
我有jQuery的,但我不知道是否有任何内置的排序帮手。我可以让每个项目的文本的二维数组
,值
和选
属性,但我不认为JavaScript的内置中的Array.sort()
将正常工作。
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.
推荐答案
选项提取到一个临时数组排序,然后重新生成列表:
Extract options into a temporary array, sort, then rebuild the list:
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);
(具体的compareFunction)和是相关的。
Mozilla's sort documentation (specifically the compareFunction) and Wikipedia's Sorting Algorithm page are relevant.
如果你想的那种不区分大小写,将文本
与 text.toLowerCase()
If you want to make the sort case insensitive, replace text
with text.toLowerCase()
上面显示的排序函数说明了如何进行排序。排序非英语语言准确地可能很复杂(参见)。使用 localeCompare 中的排序功能是一个很好的解决方案,例如:
The sort function shown above illustrates how to sort. Sorting non-english languages accurately can be complex (see the unicode collation algorithm). Using localeCompare in the sort function is a good solution, eg:
my_options.sort(function(a,b) {
return a.text.localeCompare(b.text);
});
这篇关于什么是按值一个HTML选择的选项排序的最有效的方式,而preserving当前选定的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!