使用 jQuery 按字母顺序对选项元素进行排序

问题描述:

我试图理解在 select 元素中按字母顺序对 option 元素进行排序.理想情况下,我希望将其作为一个单独的函数,我可以在其中传入 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?

我要做的是:

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

编辑 —如果要进行排序以忽略字母大小写,可以在比较之前使用 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;
});