如何隐藏<选项>在一个<选择>带有 CSS 的菜单? [英] How to hide a <option> in a <select> menu with CSS?

查看:36
本文介绍了如何隐藏<选项>在一个<选择>带有 CSS 的菜单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经意识到 Chrome 似乎不允许我在 <select> 中隐藏 <option>.Firefox 会.

I've realized that Chrome, it seems, will not allow me to hide <option> in a <select>. Firefox will.

我需要隐藏与搜索条件匹配的 <option>.在 Chrome 网络工具中,我可以看到它们被我的 JavaScript 正确设置为 display: none;,但是一旦单击 <select> 菜单,它们就会显示出来.

I need to hide the <option>s that match a search criteria. In the Chrome web tools I can see that they are correctly being set to display: none; by my JavaScript, but once then <select> menu is clicked they are shown.

如何使这些与我的搜索条件匹配的 <option> 在单击菜单时不显示?谢谢!

How can I make these <option>s that match my search criteria NOT show when the menu is clicked? Thanks!

推荐答案

你必须实现两个隐藏方法.display: none 适用于 FF,但不适用于 Chrome 或 IE.所以第二种方法是用 display: none<option> 包装在 中.FF 不会这样做(技术上无效的 HTML,根据规范),但 Chrome 和 IE 会这样做,它会隐藏该选项.

You have to implement two methods for hiding. display: none works for FF, but not Chrome or IE. So the second method is wrapping the <option> in a <span> with display: none. FF won't do it (technically invalid HTML, per the spec) but Chrome and IE will and it will hide the option.

哦,是的,我已经在 jQuery 中实现了这个:

Oh yeah, I already implemented this in jQuery:

jQuery.fn.toggleOption = function( show ) {
    jQuery( this ).toggle( show );
    if( show ) {
        if( jQuery( this ).parent( 'span.toggleOption' ).length )
            jQuery( this ).unwrap( );
    } else {
        if( jQuery( this ).parent( 'span.toggleOption' ).length == 0 )
            jQuery( this ).wrap( '<span class="toggleOption" style="display: none;" />' );
    }
};

编辑 2:以下是您将如何使用此功能:

EDIT 2: Here's how you would use this function:

jQuery(selector).toggleOption(true); // show option
jQuery(selector).toggleOption(false); // hide option

编辑 3:添加了@user1521986 建议的额外检查

EDIT 3: Added extra check suggested by @user1521986

这篇关于如何隐藏&lt;选项&gt;在一个&lt;选择&gt;带有 CSS 的菜单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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