使用jQuery按字母顺序排列选项元素 [英] Sorting options elements alphabetically using 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:
- 提取每个
< option>的文本和值。
放入一个对象数组中;
- 排序数组;
- 更新
元素的数组内容依次排列。< option> ;
- 排序数组;
- Extract the text and value of each
<option>
into an array of objects; - Sort the array;
- 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);
});
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;
});
这篇关于使用jQuery按字母顺序排列选项元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!