javascript 如何在 jquery 选择的下拉列表中按字母顺序重新排序 <options>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23394398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:48:55  来源:igfitidea点击:

How do I re-order the <options> alphabetically in a jquery-chosen dropdown

javascriptjquery-chosen

提问by John Ruddell

I have a dropdown that works just fine for what I need. The only issue I have is for all intents and purposes I cannot provide a sorted list to the dropdown, but need to order it alphabetically on the client side. I can't seem to find anything related to rearranging the tags by their value alphabetically in the chosen plugin. curious if anyone has had to do this or can point me in the right direction. sample code would be:

我有一个下拉菜单,可以很好地满足我的需要。我唯一的问题是出于所有意图和目的,我无法向下拉列表提供排序列表,但需要在客户端按字母顺序对其进行排序。我似乎找不到与在所选插件中按字母顺序重新排列标签的值相关的任何内容。好奇是否有人不得不这样做或可以指出我正确的方向。示例代码将是:

$("#my-dropdown").chosen({no_results_text: "No results matched"});

just wondering if theres an option to organize it before I go into ordering it myself in javascript. thanks in advance

只是想知道在我自己在 javascript 中订购之前是否有组织它的选项。提前致谢

回答by dana

You should sort the list first... Then run the chosen plugin.

您应该先对列表进行排序...然后运行选择的插件。

// sort list
var my_options = $("#my-dropdown option");
my_options.sort(function(a,b) {
    if (a.text > b.text) return 1;
    else if (a.text < b.text) return -1;
    else return 0
})
$("#my-dropdown").empty().append(my_options);

// run chosen plugin
$("#my-dropdown").chosen({no_results_text: "No results matched"});

List sorting code pilfered from the highly rated answer here:

列出从这里获得高度评价的答案中窃取的排序代码:

What is the most efficient way to sort an Html Select's Options by value, while preserving the currently selected item?

按值对 Html Select 的选项进行排序,同时保留当前所选项目的最有效方法是什么?

回答by Jonathan Benn

Looking at the API, I don't see any sorting option either. However, here are two links that could be helpful:

查看 API,我也没有看到任何排序选项。但是,这里有两个链接可能会有所帮助:

  1. Ricky Rosario blog post of how to sort the select options
  2. jQuery Chosen Sortable project
  1. Ricky Rosario 关于如何对选择选项进行排序的博客文章
  2. jQuery 选择 Sortable 项目