简体   繁体   English

如何对选择列表中的选项进行排序,但将其保留在顶部

[英]How to sort options in select list but keeping one at the top

Right now I have the following code that goes through my list and sort them alphabetically: 现在我有以下代码通过我的列表并按字母顺序排序:

<select id="country" class="inputList" name="country">
    <option value="">Select your country</option>
    <option value='0'>Afghanistan</option>
    <option value='1'>Albania</option>
    <option value='2'>Algeria</option>
    <option value='3'>Andorra</option>
    ...
</select>

How to make it so the script EXCLUDES the option that has NO value (the first one "Select your Country)? 如何使脚本排除没有值的选项(第一个“选择你的国家”)?

$("#country").html($("#country option").sort(function (a, b) {
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
}))

Thanks a lot! 非常感谢!

EDIT: The solution as pointed by Offbeatmammal is here: sort items in a dropdown list without the first item 编辑:Offbeatmammal指出的解决方案在这里: 在没有第一项的下拉列表中对项目进行排序

[turning comment into Answer as it solved the problem] [将评论转化为答案,因为它解决了问题]

I'd probably cheat... strip off the top one, do the sort and then put it back in ... in fact, this answer - sort items in a dropdown list without the first item - does just that 我可能会作弊...剥离顶部的一个,进行排序,然后将其重新放入...实际上,这个答案 - 在没有第一个项目的下拉列表中对项目进行排序 - 就是这样

我通常将该项目从列表中拉出来,对其余项目进行排序,然后重新插入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM