从 select jquery 中删除所有选项,但只有一个
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18866745/
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
remove all options from select jquery but only one
提问by user1428798
I have a select that contain this values:
我有一个包含以下值的选择:
<select id="lstCities" class="valid" name="City">
<option value="OSNY">OSNY</option>
<option value="dd">dd</option>
<option value="OSffNY">OSffNY</option>
<option value="ANTONY">ANTONY</option>
<option value="0">Autre...</option>
</select>
How can I delete all options but i would like to keep only
如何删除所有选项但我只想保留
<option value="0">Autre...</option>
My problem is my list is dynamic sometimes I have 3,5,7,.... select + the last one <option value="0">Autre...</option>
我的问题是我的列表是动态的,有时我有 3,5,7,.... select + 最后一个 <option value="0">Autre...</option>
回答by adeneo
回答by Arun P Johny
$('#lstCities option[value!=0]').remove()
You should remove by value and not rely on the position of the option element to keep.
您应该按值删除,而不是依赖于要保留的选项元素的位置。
回答by Cedric
If the option is always the last one, I hope this JavaScript code can help you:
如果选项总是最后一个,希望这段 JavaScript 代码可以帮助到你:
var lastNode = $("#lstCities option").last();
var option = { value:lastNode.val(), text:lastNode.text() };
$('#lstCities').find('option').remove().end().append($('<option>',{
value:option.value,
text:option.text,
}));
Learned from this post
回答by jam
This worked for me:
这对我有用:
$("#selectList option").remove();