【问题标题】:How to Hide and Show SELECT Options with JQuery in IE如何在 IE 中使用 JQuery 隐藏和显示 SELECT 选项
【发布时间】:2013-07-18 04:00:27
【问题描述】:

我正在尝试从下拉菜单中隐藏一些选项。 JQuery 的 .hide().show() 在 Firefox 和 Chrome 中运行良好,但在 IE 中没有运气。

有什么好主意吗?

【问题讨论】:

  • 我们能看到一些代码吗?

标签: jquery internet-explorer html-select


【解决方案1】:

根据浏览器检测隐藏和显示选项

在许多可能的方法中,这种方法需要浏览器嗅探,这可能不稳定,但另一方面,使用这种方法,我们不必换入和换出同一个 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/

【讨论】:

  • 这行得通,但最终更好、更清晰的跨浏览器解决方案是使用脚本实时创建、添加和删除选择项。
  • 优秀@tony :) 完美运行!
  • 这实在是太骇人听闻了,但遗憾的是,对于一个需要大量重新编码才能实现任何其他方法的项目,我能找到的唯一解决方案是。干杯。
  • 是的,这确实是 hacky。
  • 当我遇到这个愚蠢的 IE 错误时,为我节省了大量的重新编码时间。
【解决方案2】:

只是提一下 IE11 navigator.appName 返回 'Netscape' :) 所以考虑到这一点:

$("select option[value='your_option_value']").wrap((navigator.appName == 'Microsoft Internet Explorer' || navigator.appName == 'Netscape') ? '<span>' : null).hide();

【讨论】:

【解决方案3】:

我找到了一个相当简单的解决方案,虽然选项不会被隐藏,而是在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-09
    • 1970-01-01
    • 1970-01-01
    • 2012-12-17
    • 2015-06-23
    相关资源
    最近更新 更多