3 回答
尝试这个
var select = document.getElementById('select');
var sorted = Array.prototype.slice.call(select.options).sort(function(a, b) {
if(a.label < b.label) return -1;
if(a.label > b.label) return 1;
return 0;
});
for(var i = 0; i < sorted.length; i++) {
select.add(sorted[i]);
}
按标签排序。只需将其更改为其他属性。
注意options
是只读的。
注意:不适用于 IE 8 及以下版本
试试这个。
var select = document.getElementById("example-select");
var options = select.options;
var newOption = new Option('Text 1', 'Value1');
for (var i = 0, len = options.length; i < len; i++) {
if (newOption.text.localeCompare(options[i].text) < 0) {
break;
}
}
select.insertBefore(newOption, options[i] || null);
There are a couple of methods, one is to create an array of the option values (or text, whatever you want to sort on) and create an object with properties whose names are the option values (or text) and values are references to the options.
Sort the array, then iterate over it, using the member values to get the options from the object, e.g.
function sortOptionsByValue(select) {
var a = [], o = {}, opt;
for (var i=0, iLen=select.options.length; i<iLen; i++) {
opt = select.options[i];
a.push(opt.value);
o[opt.value] = opt;
}
a.sort();
while (i--) {
select.insertBefore(o[a[i]], select.firstChild);
}
// Optional, make first option selected
select.selectedIndex = 0;
}
There are other methods, the above is just one. But it will work in any ECMA-262 compliant browser and doesn't depend on host objects acting like native objects, only that they behave like the W3C DOM Core says they should.