jQuery 隐藏选择中的第一个选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26785655/
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
Hide first option in select
提问by Ahmar Ali
I have options in a drop down which are generated dynamically. I want to hide first option as that is not needed. Is there any cross browser compatible method to achieve this. Any solution would be good whether using jquery or css.
我在下拉列表中有动态生成的选项。我想隐藏第一个选项,因为不需要。是否有任何跨浏览器兼容的方法来实现这一点。无论是使用 jquery 还是 css,任何解决方案都会很好。
Ahmar
艾哈迈尔
回答by Jasper
$("#my-drop-down-select-element-id").find("option").eq(0).remove();
You can remove the first <option />
element in a <select />
element with the above code.
您可以使用上述代码删除<option />
元素中的第一个<select />
元素。
Using CSS to hide <option />
elements is problematic. See the link below for more on this.
使用 CSS 隐藏<option />
元素是有问题的。有关更多信息,请参阅下面的链接。
To break-down the above function chain:
分解上述功能链:
- Select the
<select />
element. (No pun intended) - Find
<option />
elements within the previously selected element. I usedfind()
because if there are option groups thenchildren()
won't work. - Filter down to only the first
<option />
element. - Remove that element from the DOM.
- 选择
<select />
元素。(无双关语) <option />
在先前选择的元素中查找元素。我使用find()
是因为如果有选项组然后children()
将无法工作。- 过滤到仅第一个
<option />
元素。 - 从 DOM 中删除该元素。
This has definitely been asked before, for some more reading: How to hide a <option> in a <select> menu with CSS?
之前肯定有人问过这个问题,需要更多阅读:如何使用 CSS 在 <select> 菜单中隐藏 <option>?
回答by Gael
$('select > option:first').hide();
All your first select option hidden with this.
所有你的第一个选择选项都隐藏了。
回答by Zanoldor
HTML
HTML
<select id='test'>
<option value='1'> op 1 </option>
<option value='2'> op 2 </option>
<option value='3'> op 3 </option>
<option value='4'> op 4 </option>
</select>
Jquery
查询
$(document).ready(function() {
$("#test").find("option").eq(0).remove();
});
that's it!
就是这样!
回答by Hive7
What you can do is use CSS like this as it works in sync with the select loading like this:
您可以做的是像这样使用 CSS,因为它与这样的选择加载同步工作:
#select-item:first-child {
display: none;
}