javascript 选择框隐藏下拉菜单中的第一个选项条目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7804111/
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
Selectbox hide first option entry on dropdown?
提问by acctman
Is it possible to hide the first option i.e. <option>Select One</option>
when the user clicks the dropdown box to see the options. So the text Select Onedoes not appear in the list
是否可以隐藏第一个选项,即<option>Select One</option>
当用户单击下拉框以查看选项时。所以文本Select One不会出现在列表中
回答by James Allardice
As there is no reliable cross browser way to hide option
elements, your best bet is to remove it on focus
and add it again on blur
:
由于没有可靠的跨浏览器隐藏option
元素的方法,最好的办法是将其删除focus
并重新添加blur
:
jQuery(document).ready(function () {
var first = jQuery('#myselect').find('option').first();
jQuery('#myselect').on('focus', function (e) {
first.remove();
}).on('blur', function (e) {
jQuery(this).find('option').first().before(first);
});
});
Here's a working example
这是一个工作示例
回答by Sujan Mhrzn
You can use your plain HTML for hiding the first Element of option when select is opened as:
您可以使用纯HTML隐藏选择打开时选择的第一个元素:
<select name="list">
<option selected="selected" hidden>First Element</option>
<option>Second Element</option>
<option>Third Element</option>
</select>
Here is the working fiddle: https://jsfiddle.net/sujan_mhrzn/y5kxtkc6/
回答by Stuart Harrison
As a quick CSS option you could give the dropdown an id and then
作为一个快速的 CSS 选项,你可以给下拉菜单一个 id,然后
#cat option:first-child {
display: none;
}
The above uses #cat as the id for the dropdown
以上使用 #cat 作为下拉列表的 id
回答by Andy E
The only cross-browser method is to remove it entirely. In plain ol' JS:
唯一的跨浏览器方法是完全删除它。在普通的 ol' JS 中:
var sel = document.getElementById("mySelect");
sel.onfocus = function () {
select.onfocus = null;
sel.removeChild(sel.firstChild);
}
jQuery:
jQuery:
$("#mySelect").focus(function () {
$(this).remove(this.firstChild).unbind(arguments.callee);
});
回答by Nikoloff
If you want to remove the option, the simples code would be:
如果要删除该选项,简单的代码将是:
var mySelect = document.getElementById('mySelect');
mySelect.onfocus = function() { mySelect.removeChild(mySelect.options[0]); }
where mySelect
is the id of the select box.
mySelect
选择框的 id在哪里。
Edit: I changed the code to append an event listener for the focus event. This code, however, will remove the first option everytime you select the select box. Pretty sure this is not what you need. You could use onblur to append the option again, but I don't know if that's what you need. Please clarify what you want to do.
编辑:我更改了代码以附加焦点事件的事件侦听器。但是,此代码将在您每次选择选择框时删除第一个选项。很确定这不是您所需要的。您可以使用 onblur 再次附加选项,但我不知道这是否是您需要的。请说明你想做什么。