且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用jQuery按字母顺序排列选项元素

更新时间:2023-10-24 23:35:58

我会做的是:

What I'd do is:


  1. 提取每个< option>的文本和值。 放入一个对象数组中;
  2. 排序数组;
  3. 更新< option&gt ;
  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()$ c $比较之前的函数:

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