按字母顺序排列选择菜单? [英] sort select menu alphabetically?

查看:104
本文介绍了按字母顺序排列选择菜单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 < select> 
< option value =volvo>汽车< / option>
< option value =saab> ------------< / option>
< option value =volvo>沃尔沃< / option>
< option value =saab> Saab< / option>
< option value =mercedes> Mercedes< / option>
< option value =audi> Audi< / option>
< / select>

使用Javascript,我将如何按字母顺序重新排序列表,不包括前两个选项( Cars ------- ),它们必须保留在顶部?作为一个纯粹主义者,我会说在任何时候jQuery都没有特别提到或要求提供,由于某种原因,这个项目可能无法使用。

 函数sortlist(){

var cl = document.getElementById ( '卡洛斯');
var clTexts = new Array();

for(i = 2; 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 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/



已更新以保持个案中立。

>

I've got the following select menu (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 (Cars and -------), which must remain at the top? Thanks in advance for any help.

解决方案

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.

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/

Updated to be case neutral.

这篇关于按字母顺序排列选择菜单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆