javascript JQuery - 从 Selectbox 中删除所有选项,除了 first 和 selected

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

JQuery - Remove all option from Selectbox except for first and selected

javascriptjqueryhtml

提问by bos570

I have a html select box with several options. Upon selection of an option I want Only the selected option and the first option to be shown in the select option dropdown. I know how to filter and show only one option but I cannot figure out how to include both option where the 'selected' option remains 'selected'. I have include snippets similar to of my code as well as a demo.

我有一个带有多个选项的 html 选择框。选择一个选项后,我只想在选择选项下拉列表中显示所选选项和第一个选项。我知道如何过滤并只显示一个选项,但我无法弄清楚如何在“选定”选项保持“选定”状态的情况下包含这两个选项。我已经包含了类似于我的代码的片段以及一个演示。

HTML:

HTML:

<select id="myDropdown">
<option selected>Select fruit</option>
<option>Grapes</option>
<option>Bananas</option>
<option>Oranges</option>
<option>Apples</option>
</select>

JS:

JS:

$(document).on('change', '#myDropdown', function() {
    $('option', this).not(this,'option:gt(0)').siblings().remove(); });

I am trying to use the first option to perform another function 'on change' so I need the selected option to remain selected while the rest being filtered out except for the first. For example if 'Oranges' were selected, this is what you would see:

我正在尝试使用第一个选项来执行另一个“更改时”功能,因此我需要选择的选项保持选中状态,而其余选项将被过滤掉,但第一个除外。例如,如果选择了“Oranges”,您将看到以下内容:

<select id="myDropdown">
     <option>Select fruit</option>
     <option>Oranges</option>  //selcted value
</select>

BTW I am using jquery mobile to style as well.

顺便说一句,我也在使用 jquery mobile 来设计样式。

jsfiddle

提琴手

回答by Stryner

.notonly takes 1 parameter. If you want to filter on two different selectors, you can add a comma between them inside the string. You can also use the :selectedselector:

.not只需要 1 个参数。如果要过滤两个不同的选择器,可以在字符串内在它们之间添加逗号。您还可以使用:selected选择器:

$('option', this).not(':eq(0), :selected').remove();

See Updated Fiddle: http://jsfiddle.net/znx9hxvu/9/

请参阅更新的小提琴:http: //jsfiddle.net/znx9hxvu/9/