jQuery “visible” doesn't work in all browsers,

2019-02-18 06:33发布

I've made a very simple fiddle here, and you can check it out in different browsers.

It only works in Firefox. In other words, seems that $('#select-tag-id option:visible') doesn't work in other browsers. What's wrong? Is it a jQuery bug?

The code is:

<select id='items'>
    <option value='1' style='display: none;'>One</option>
    <option value='1' style='display: block;'>Two</option>
    <option value='1' style='display: block;'>Three</option>
    <option value='1' style='display: none;'>Four</option>
</select>

and the JavaScript (jQuery code) is:

$(function(){
    alert($('#items option:visible').length);
});

2条回答
聊天终结者
2楼-- · 2019-02-18 07:20

Indeed, :hidden and :visible don't work on <option>'s

You could try to use disabled="disabled" see:

http://jsfiddle.net/sZR2f/7/

查看更多
手持菜刀,她持情操
3楼-- · 2019-02-18 07:31

It's not a jQuery bug - just (yet another) browser difference.

IE won't let you set display:none on option elements (style.display='none' doesnt work on option tags).

If you look at your fiddle in both FF and IE, you'll see that the <select> still contains all four elements in IE, but only two in FF, regardless of jQuery being present.

The solution would probably be to actually remove the elements and replace when needed.

查看更多
登录 后发表回答