更新时间:2023-10-24 23:35:58
我会做的是:
What I'd do is:
< option>的文本和值。
放入一个对象数组中; < option> ;
<option>
into an array of objects;<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);
});
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;
});