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

2019-04-10 12:51发布

问题:

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);
});

回答1:

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.



回答2:

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

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

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