如何在IE中使用JQuery隐藏和显示SELECT选项

8

我正在尝试隐藏下拉菜单中的一些选项。在Firefox和Chrome浏览器中,JQuery的.hide().show()效果很好,但是在IE浏览器中没有成功。

有什么好的建议吗?


2
我们可以看到一些代码吗? - Farhan Ahmad
3个回答

12

基于浏览器检测隐藏和显示选项

虽然有许多可能的方法,但该方法需要对浏览器进行嗅探,这可能不太稳定,但另一方面,使用此方法我们不必交替使用多个相同的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 Brasunas
1
太棒了 @tony :) 完美运行! - Karthi Skb
当我遇到这个愚蠢的IE bug时,这个节省了我很多重新编码的时间。 - Abdul Hameed
嗨,我尝试在Internet Explorer 11上运行此代码...但是对于I.E. 11,navigator.appName是“Netscape”... - Didier68
测试IE 11,请阅读:https://dev59.com/b2Qm5IYBdhLWcg3wowWw#17447718 - Didier68
显示剩余2条评论

3

仅提醒一下,IE11的navigator.appName返回的是“Netscape”:) 因此需要考虑以下问题:

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

1
这是一个很好的观点。然而,其他浏览器也可以选择在此处返回“Netscape”(https://dev59.com/a2Uq5IYBdhLWcg3wV_Ei),因此你的结果可能会有所不同。 - Tony Brasunas

0

我找到了一个相当简单的解决方案,尽管在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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接