$(“#id option”).hide(); not working on safari/chro

2019-01-15 11:44发布

问题:

Same for:

$("#id option").show();

I'm just surprised. I thought that something went wrong with my code. I tried it with a blank html:

<select id = "name">
  <option>1</option>
  <option>2</option>
</select>

Javascript:

​$("#name option").hide();​

http://jsfiddle.net/kgLkt/

It works like a charm with firefox, but not on safari nor chrome!

Is there a substitute?!

EDIT: I need to hide/show the option (or some of them) from appearing in the list.

回答1:

To hide:

var myOpts = $("#id option").detach();

To show:

$("#id option").append(myOpts);

As opposed to .remove(), .detach() keeps all jQuery data associated with the removed elements.



回答2:

With the standard select I don't think there is any cross browser way to hide a select option.

You could look for a custom select control or you could keep the full list of items on a separated variable and remove / add items from the select as you need.



回答3:

Hmmm. Could be an implementation issue...

Perhaps try

$("#name option").remove();

if you need to maintain some knowledge of what has been removed then load them into a variable before hand.

var $opts = $("#name option");

you could then use index to add them back in:

$("#name").append( $opts.eq(n) );


回答4:

You didn't select jQuery in the fiddle. Anyhow, you need to set selectedIndex of the <select> to -1 to clear the currently selected option: http://jsfiddle.net/kgLkt/2/.

$("#name option").hide().parent().prop("selectedIndex", -1);​​​​​​


回答5:

This will work on safari

   var select = $('#name');
    var diff = 0;
    console.dir(select[0].options);
    select.find('option').each(function(x) {
        select[0].options[x+diff] = null;
        diff -= 1;
    });