【发布时间】:2013-07-18 04:00:27
【问题描述】:
我正在尝试从下拉菜单中隐藏一些选项。 JQuery 的 .hide() 和 .show() 在 Firefox 和 Chrome 中运行良好,但在 IE 中没有运气。
有什么好主意吗?
【问题讨论】:
-
我们能看到一些代码吗?
标签: jquery internet-explorer html-select
我正在尝试从下拉菜单中隐藏一些选项。 JQuery 的 .hide() 和 .show() 在 Firefox 和 Chrome 中运行良好,但在 IE 中没有运气。
有什么好主意吗?
【问题讨论】:
标签: jquery internet-explorer html-select
根据浏览器检测隐藏和显示选项
在许多可能的方法中,这种方法需要浏览器嗅探,这可能不稳定,但另一方面,使用这种方法,我们不必换入和换出同一个 select 列表的多个副本。
//To hide elements
$("select option").each(function(index, val){
if ($(this).is('option') && (!$(this).parent().is('span')))
$(this).wrap((navigator.appName == 'Microsoft Internet Explorer') ? '<span>' : null).hide();
});
//To show elements
$("select option").each(function(index, val) {
if(navigator.appName == 'Microsoft Internet Explorer') {
if (this.nodeName.toUpperCase() === 'OPTION') {
var span = $(this).parent();
var opt = this;
if($(this).parent().is('span')) {
$(opt).show();
$(span).replaceWith(opt);
}
}
} else {
$(this).show(); //all other browsers use standard .show()
}
});
这要归功于 Dima Svirid:http://ajax911.com/hide-options-selecbox-jquery/
【讨论】:
只是提一下 IE11 navigator.appName 返回 'Netscape' :) 所以考虑到这一点:
$("select option[value='your_option_value']").wrap((navigator.appName == 'Microsoft Internet Explorer' || navigator.appName == 'Netscape') ? '<span>' : null).hide();
【讨论】:
我找到了一个相当简单的解决方案,虽然选项不会被隐藏,而是在 IE 上被禁用。
$('#delivery_time option[value="06:30"]').removeAttr('disabled').show(); // To Show/Enable
$('#delivery_time option[value="06:30"]').attr('disabled', 'disabled').hide(); // To Hide/Disable
这是我偶然发现这两行的来源:IT Support Guides - Internet Explorer – How to hide select options using jQuery
【讨论】: