按值对 Html Select 的选项进行排序,同时保留当前所选项目的最有效方法是什么? [英] What is the most efficient way to sort an Html Select's Options by value, while preserving the currently selected item?

查看:30
本文介绍了按值对 Html Select 的选项进行排序,同时保留当前所选项目的最有效方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 jQuery,但我不确定它是否有任何内置的排序助手.我可以为每个项目的 textvalueselected 属性创建一个二维数组,但我不认为 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);

Mozilla 的排序文档(特别是 compareFunction)和 维基百科的排序算法页面是相关的.

Mozilla's sort documentation (specifically the compareFunction) and Wikipedia's Sorting Algorithm page are relevant.

如果您想让排序不区分大小写,请将 text 替换为 text.toLowerCase()

If you want to make the sort case insensitive, replace text with text.toLowerCase()

上面显示的排序函数说明了如何排序.准确地对非英语语言进行排序可能很复杂(请参阅 unicode 整理算法).在排序函数中使用 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 Select 的选项进行排序,同时保留当前所选项目的最有效方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆