如何使用JavaScript隐藏选择选项? (跨浏览器) [英] How can I hide select options with JavaScript? (Cross browser)

查看:127
本文介绍了如何使用JavaScript隐藏选择选项? (跨浏览器)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这应该工作:

$('option').hide(); // hide options

它可以在Firefox中使用,但不能在Chrome中使用)。

It works in Firefox, but not Chrome (and probably not in IE, not tested).

一个更有趣的例子:

<select>
    <option class="hide">Hide me</option>
    <option>visible option</option>
</select>
<script type="text/javascript">
// try to hide the first option
$('option.hide').hide();

// to select the first visible option
$('option:visible').first().attr('selected', 'selected');
</script>

或参阅 http://jsfiddle.net/TGxUf/

是从DOM分离选项元素的唯一选项吗?

Is the only option to detach the option elements from the DOM? I need to show them again later, so this would not be very effective.

推荐答案

不幸的是,你不能隐藏<$

Unfortunately, you can't hide option elements in all browsers.

在过去,当我需要这样做的时候,我已经设置了它们的 disabled 属性,如此...

In the past when I have needed to do this, I have set their disabled attribute, like so...

$('option').prop('disabled', true);

然后我使用这个CSS在浏览器中支持隐藏

I've then used the hiding where it is supported in browsers using this piece of CSS...

select option[disabled] {
    display: none;
}

这篇关于如何使用JavaScript隐藏选择选项? (跨浏览器)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆