JQuery - 从Selectbox中删除除first和selected之外的所有选项

时间:2015-07-22 15:31:05

标签: javascript jquery html

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

HTML:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    if(self.view.bounds.width > 400){
        return CGSize(width:self.view.bounds.width/3-10, height:self.view.bounds.width/3-10)
    }
    return CGSize(width:self.view.bounds.width/2-10, height:self.view.bounds.width/2-10)
}

JS:

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

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

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

BTW我也在使用jquery mobile来设计样式。

jsfiddle

1 个答案:

答案 0 :(得分:15)

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

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

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