使用jQuery按字母顺序排列选项元素 [英] Sorting options elements alphabetically using jQuery

查看:99
本文介绍了使用jQuery按字母顺序排列选项元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解按字母顺序排列元素中的选项元素的选择元素。理想情况下,我想把它作为一个单独的函数,我可以传入select元素,因为当用户单击某些按钮时需要对它进行排序。

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.

我已经搜索了一个很好的方法来做到这一点,但一直没有找到适合我的任何东西。

I've searched high and low for a good way of doing this, but haven't been able to find anything that worked for me.

应该对选项元素进行排序按字母顺序排列的文本,而不是值。

The option elements should be sorted alphabetically by text, not value.

这是否可能以某种方式?

Is this possible in some way?

推荐答案

我会做的是:

What I'd do is:


  1. 提取每个< option>的文本和值。 放入一个对象数组中;
  2. 排序数组;
  3. 更新< option> ;
  4. 元素的数组内容依次排列。
  1. Extract the text and value of each <option> into an array of objects;
  2. Sort the array;
  3. Update the <option> elements with the array contents in order.

使用jQuery可以做到这一点:

To do that with jQuery, you could do this:

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);
});

这是一个可以工作的jsfiddle。

edit —如果您想排序以便忽略字母大小写,您可以使用JavaScript .toUpperCase() .toLowerCase()

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按字母顺序排列选项元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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