Javascript 使用 jQuery 按字母顺序排序选项元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12073270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sorting options elements alphabetically using jQuery
提问by bomortensen
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.
我正在尝试按字母顺序理解option
元素内的排序元素select
。理想情况下,我希望将其作为一个单独的函数,我可以在其中传入 select 元素,因为当用户单击某些按钮时需要对其进行排序。
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?
这在某种程度上可能吗?
回答by Pointy
What I'd do is:
我要做的是:
- 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.
- 将每个的文本和值提取
<option>
到一个对象数组中; - 对数组进行排序;
<option>
按顺序更新具有数组内容的元素。
To do that with jQuery, you could do this:
要使用 jQuery 做到这一点,您可以这样做:
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— If you want to sort such that you ignore alphabetic case, you can use the JavaScript .toUpperCase()
or .toLowerCase()
functions before comparing:
编辑- 如果要排序以忽略字母大小写,可以在比较之前使用 JavaScript.toUpperCase()
或.toLowerCase()
函数:
arr.sort(function(o1, o2) {
var t1 = o1.t.toLowerCase(), t2 = o2.t.toLowerCase();
return t1 > t2 ? 1 : t1 < t2 ? -1 : 0;
});
回答by marxin
Accepted answer is not the best in all cases because sometimes you want to perserve classes of options and different arguments (for example data-foo).
接受的答案并非在所有情况下都是最好的,因为有时您希望保留选项类别和不同的参数(例如 data-foo)。
My solution is:
我的解决办法是:
var sel = $('#select_id');
var selected = sel.val(); // cache selected value, before reordering
var opts_list = sel.find('option');
opts_list.sort(function(a, b) { return $(a).text() > $(b).text() ? 1 : -1; });
sel.html('').append(opts_list);
sel.val(selected); // set cached selected value
//For ie11 or those who get a blank options, replace html('') empty()
//对于ie11或者得到空白选项的,替换html('') empty()
回答by Diode
<select id="mSelect" >
<option value="val1" > DEF </option>
<option value="val4" > GRT </option>
<option value="val2" > ABC </option>
<option value="val3" > OPL </option>
<option value="val5" > AWS </option>
<option value="val9" > BTY </option>
</select>
.
.
$("#mSelect").append($("#mSelect option").remove().sort(function(a, b) {
var at = $(a).text(), bt = $(b).text();
return (at > bt)?1:((at < bt)?-1:0);
}));
回答by Gerbus
html:
html:
<select id="list">
<option value="op3">option 3</option>
<option value="op1">option 1</option>
<option value="op2">option 2</option>
</select>
jQuery:
jQuery:
var options = $("#list option"); // Collect options
options.detach().sort(function(a,b) { // Detach from select, then Sort
var at = $(a).text();
var bt = $(b).text();
return (at > bt)?1:((at < bt)?-1:0); // Tell the sort function how to order
});
options.appendTo("#list"); // Re-attach to select
I used tracevipin's solution, which worked fantastically. I provide a slightly modified version here for anyone like me who likes to find easily readable code, and compress it afterit's understood. I've also used .detach
instead of .remove
to preserve any bindings on the option DOM elements.
我使用了 tracevipin 的解决方案,效果非常好。我在这里为像我这样喜欢找到易于阅读的代码并在理解后对其进行压缩的人提供了一个稍微修改的版本。我还使用了.detach
而不是.remove
保留选项 DOM 元素上的任何绑定。
回答by Victor BV
Here's my improved version of Pointy's solution:
这是我改进的Pointy 解决方案版本:
function sortSelectOptions(selector, skip_first) {
var options = (skip_first) ? $(selector + ' option:not(:first)') : $(selector + ' option');
var arr = options.map(function(_, o) { return { t: $(o).text(), v: o.value, s: $(o).prop('selected') }; }).get();
arr.sort(function(o1, o2) {
var t1 = o1.t.toLowerCase(), t2 = o2.t.toLowerCase();
return t1 > t2 ? 1 : t1 < t2 ? -1 : 0;
});
options.each(function(i, o) {
o.value = arr[i].v;
$(o).text(arr[i].t);
if (arr[i].s) {
$(o).attr('selected', 'selected').prop('selected', true);
} else {
$(o).removeAttr('selected');
$(o).prop('selected', false);
}
});
}
The function has the skip_first
parameter, which is useful when you want to keep the first option on top, e.g. when it's "choose below:".
该函数具有skip_first
参数,当您想将第一个选项保留在顶部时很有用,例如当它是“选择下面:”时。
It also keeps track of the previously selected option.
它还跟踪先前选择的选项。
Example usage:
用法示例:
jQuery(document).ready(function($) {
sortSelectOptions('#select-id', true);
});
回答by Kuxa
I know this topic is old but I think my answer can be useful for a lot of people.
我知道这个话题很老,但我认为我的回答对很多人都有用。
Here is jQuery plugin made from Pointy's answer using ES6:
这是使用 ES6根据Pointy的回答制作的 jQuery 插件:
/**
* Sort values alphabetically in select
* source: http://stackoverflow.com/questions/12073270/sorting-options-elements-alphabetically-using-jquery
*/
$.fn.extend({
sortSelect() {
let options = this.find("option"),
arr = options.map(function(_, o) { return { t: $(o).text(), v: o.value }; }).get();
arr.sort((o1, o2) => { // sort select
let t1 = o1.t.toLowerCase(),
t2 = o2.t.toLowerCase();
return t1 > t2 ? 1 : t1 < t2 ? -1 : 0;
});
options.each((i, o) => {
o.value = arr[i].v;
$(o).text(arr[i].t);
});
}
});
Use is very easy
使用非常简单
$("select").sortSelect();
回答by rmirabelle
None of the answers worked for me. For some strange reason, when looping through the options, each option returns nothing when text()
is called. Instead, I was forced to retrieve the option's label via attr('label')
没有一个答案对我有用。出于某种奇怪的原因,在循环选项时,每个选项在text()
被调用时都不返回任何内容。相反,我被迫通过以下方式检索选项的标签attr('label')
/**
* Sort the options of the target select list
* alphabetically by label. For some reason, when
* we call detach(), the returned options have no
* text() and instead we're forced to get the option's
* label via the 'label' attribute.
* @param select jQuery selector
*/
function sort_multi_select(select) {
var options = select.find('option');
options.detach().sort(function (a, b) {
var at = $(a).attr('label'), //label, not text()
bt = $(b).attr('label');
return at > bt ? 1 : at < bt ? -1 : 0;
});
options.appendTo(select);
}
//example
sort_multi_select($('#my_select'));
回答by Dr Fred
Malakgeorge answer is nice an can be easily wrapped into a jQuery function:
Malakgeorge 的回答很好,可以轻松地包装到 jQuery 函数中:
$.fn.sortSelectByText = function(){
this.each(function(){
var selected = $(this).val();
var opts_list = $(this).find('option');
opts_list.sort(function(a, b) { return $(a).text() > $(b).text() ? 1 : -1; });
$(this).html('').append(opts_list);
$(this).val(selected);
})
return this;
}
回答by shali ravi
Yes you can sort the options by its text and append it back to the select box.
是的,您可以按其文本对选项进行排序并将其附加回选择框。
function NASort(a, b) {
if (a.innerHTML == 'NA') {
return 1;
}
else if (b.innerHTML == 'NA') {
return -1;
}
return (a.innerHTML > b.innerHTML) ? 1 : -1;
};
回答by Sam Tyson
The jquery.selectboxes.jsplugin has a sort method. You can implement the plugin, or dive into the code to see a way to sort the options.
该jquery.selectboxes.js插件有一个排序方法。您可以实现插件,或深入代码以查看对选项进行排序的方法。