I'm trying to understand sorting option elements within a select element alphabetically. Ideally, I'd like to have this as a separate function where I can just pass in the select element since it needs to be sorted when the user clicks some buttons.

我到处寻找一种很好的方法,但没有找到任何适合我的方法.

选项元素应按文本的字母顺序排序,而不是按值排序.

Is this possible in some way?

推荐答案

What I'd do is:

  1. 将每个<option>的文本和值提取到一个对象数组中;
  2. 对数组进行排序;
  3. 按顺序用数组内容更新<option>个元素.

要使用jQuery实现这一点,可以执行以下操作:

var options = $('select.whatever option');
var arr = options.map(function(_, o) { return { t: $(o).text(), v: o.value }; }).get();
arr.sort(function(o1, o2) { return o1.t > o2.t ? 1 : o1.t < o2.t ? -1 : 0; });
options.each(function(i, o) {
  o.value = arr[i].v;
  $(o).text(arr[i].t);
});

Here is a working jsfiddle.

edit — If you want to sort such that you ignore alphabetic case, you can use the JavaScript .toUpperCase() or .toLowerCase() functions before comparing:

arr.sort(function(o1, o2) {
  var t1 = o1.t.toLowerCase(), t2 = o2.t.toLowerCase();

  return t1 > t2 ? 1 : t1 < t2 ? -1 : 0;
});

Jquery相关问答推荐

使用 jQuery 时何时/为什么要在变量前加上$?

如何使用 JQuery Select 没有特定子元素的元素

jQuery 的元素或类 LIKE Select 器?

何时执行 $(document).ready 回调?

JQuery通过类名获取所有元素

jQuery 的 ajax 默认超时值是多少?

jQuery增量读取AJAX流?

使用 jQuery 将行添加到表的 tbody

如何正确卸载/销毁 VIDEO 元素

jQuery scrollTop 在 Chrome 中不工作但在 Firefox 中工作

延迟后运行功能

jQuery中的Grep与过滤器?

Jquery 和 HTML FormData 返回未捕获的 TypeError:非法调用

使用带有 HTML 表格的 jQuery UI 可排序

jQuery.extend 和 jQuery.fn.extend 的区别?

jQuery UI 工具提示不支持 html 内容

jQuery : eq() 与 get()

如何使锚链接不可点击或禁用?

表单 propType 失败:您在没有 `onChange` 处理程序的情况下向表单字段提供了 `value` props

使用中键触发 onclick 事件