Javascript 按字母顺序排序选择菜单?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5248189/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:21:19  来源:igfitidea点击:

sort select menu alphabetically?

javascripthtmlselect

提问by Skizit

I've got the following select menu (jsFiddle):

我有以下选择菜单(jsFiddle):

<select>
  <option value="volvo">Cars</option>
  <option value="saab">------------</option>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

Using Javascript, how would I re-sort the list alphabetically, excluding the first 2 options (Carsand -------), which must remain at the top? Thanks in advance for any help.

使用 Javascript,我将如何按字母顺序重新排序列表,不包括前两个选项 (Cars-------),它们必须保留在顶部?在此先感谢您的帮助。

回答by Jeff Parker

Being a purist, I would say that at no point was jQuery specifically mentioned or asked for, it may not be in use in this project for one reason or another. Here's an example using pure javascript.

作为一个纯粹主义者,我会说在任何时候都没有特别提到或要求 jQuery,它可能出于某种原因没有在这个项目中使用。这是一个使用纯 javascript 的示例。

function sortlist(){

 var cl = document.getElementById('carlist');
 var clTexts = new Array();

 for(i = 2; i < cl.length; i++){
    clTexts[i-2] =
        cl.options[i].text.toUpperCase() + "," +
        cl.options[i].text + "," +
        cl.options[i].value + "," +
        cl.options[i].selected;
 }

 clTexts.sort();

 for(i = 2; i < cl.length; i++){
    var parts = clTexts[i-2].split(',');

    cl.options[i].text = parts[1];
    cl.options[i].value = parts[2];
    if(parts[3] == "true"){
        cl.options[i].selected = true;
    }else{
       cl.options[i].selected = false;
    }
 }
}

sortlist();

http://jsfiddle.net/GAYvL/7/

http://jsfiddle.net/GAYvL/7/

Updatedto be case neutral.

更新为不区分大小写。

回答by Eric Di Bari

I would start by giving a class name to all of the entries I want to sort, and giving and ID to the select:

我将首先为我想要排序的所有条目提供一个类名,并为选择提供一个 ID:

 <select id="sortableCars">
   <option value="volvo">Cars</option>
   <option class="sortMe" value="saab">------------</option>
   <option class="sortMe" value="volvo">Volvo</option>
   <option class="sortMe" value="saab">Saab</option>
   <option class="sortMe" value="mercedes">Mercedes</option>
   <option class="sortMe" value="audi">Audi</option>
 </select>

as for the javascript

至于javascript

 var mylist = $('#sortableCars');
 var listitems = mylist.children('option.sortMe').get();
 listitems.sort(function(a, b) {
    var compA = $(a).text().toUpperCase();
    var compB = $(b).text().toUpperCase();
    return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
 })
 $.each(listitems, function(idx, itm) { mylist.append(itm); });

回答by Andy E

My first approach was similar to Koolinc's, using Array.prototype.slice to convert the <select>element's children NodeList to an array. However, this doesn't work in Internet Explorer 8 and lower so I changed it to extract, sort and then re-insert:

我的第一种方法类似于 Koolinc 的方法,使用 Array.prototype.slice 将<select>元素的子节点NodeList 转换为数组。但是,这在 Internet Explorer 8 及更低版本中不起作用,因此我将其更改为提取、排序然后重新插入:

var sel = document.getElementsByTagName("select")[0],
    opts = [];

// Extract the elements into an array
for (var i=sel.options.length-1; i >= 2; i--)
    opts.push(sel.removeChild(sel.options[i]));

// Sort them
opts.sort(function (a, b) { 
    return a.innerHTML.localeCompare(b.innerHTML);
});

// Put them back into the <select>
while(opts.length)
    sel.appendChild(opts.shift());

Working demo: http://jsfiddle.net/3YjNR/2/

工作演示:http: //jsfiddle.net/3YjNR/2/

回答by Renato Gama

This is just a more generic answser based on @Jeff Parker's one!

这只是一个基于@Jeff Parker 的更通用的答案!

function sortSelect(select, startAt) {
    if(typeof startAt === 'undefined') {
        startAt = 0;
    }

    var texts = [];

    for(var i = startAt; i < select.length; i++) {
        texts[i] = [
            select.options[i].text.toUpperCase(),
            select.options[i].text,
            select.options[i].value
        ].join('|');
    }

    texts.sort();

    texts.forEach(function(text, index) {
        var parts = text.split('|');

        select.options[startAt + index].text = parts[1];
        select.options[startAt + index].value = parts[2];
    });
}

I have also created a fiddle; http://jsfiddle.net/4u86B/1/

我还创建了一个小提琴;http://jsfiddle.net/4u86B/1/