Javascript 如何隐藏 optgroup/option 元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2731668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:41:56  来源:igfitidea点击:

How to hide optgroup/option elements?

javascriptjqueryhtmloptionoptgroup

提问by DisgruntledGoat

Is there a way to hide optionor optgroupHTML elements? I've tried calling hide()in jQuery, and also using regular Javascript to set style.display='none'.

有没有办法隐藏optionoptgroupHTML 元素?我试过hide()在 jQuery 中调用,并使用常规的 Javascript 来设置style.display='none'.

It works in Firefox but not in any other browsers. Actually removing them from the DOM doeswork, so perhaps there's a way to save each DOM element when it's removed, and reinsert them in the same place?

它适用于 Firefox,但不适用于任何其他浏览器。实际上从 DOM删除它们确实有效,所以也许有一种方法可以在删除每个 DOM 元素时保存它,然后将它们重新插入到同一位置?

My HTML is like this:

我的 HTML 是这样的:

<select name="propsearch[area]" id="propsearch_area">
    <option value="0">- Any -</option>
    <optgroup label="Bristol">
        <option  value="Hotwells">Hotwells</option>
        <option  value="Montpelier">Montpelier</option>
    </optgroup>
    <optgroup label="Cardiff">
        <option  value="Heath">Heath</option>
        <option  value="Roath">Roath</option>
    </optgroup>
    <optgroup label="Exeter">
        <option  value="Pennsylvania Road">Pennsylvania Road</option>
        <option  value="Lower North Street">Lower North Street</option>
    </optgroup>
    <optgroup label="Swansea">
        <option  value="Brynmill">Brynmill</option>
        <option  value="Uplands">Uplands</option>
    </optgroup>
</select>

采纳答案by Vlado Tovarnak

I figured that this solution works fine for me:

我认为这个解决方案对我来说很好用:

Make another select e.g.

做另一个选择,例如

$("#footer_canvas").after('<select id="parkingLot"></select>');

then hide it

然后隐藏它

$("#parkingLot").hide();

When you want to 'hide' some optgroup, just 'park' it in this hidden select.

当您想“隐藏”某些 optgroup 时,只需将其“停放”在此隐藏选择中即可。

$('#VehicleVehicleCategoryId optgroup[label="kategorie L"]').appendTo("#parkingLot");

Same way you can make it visible. This is just the snippets of my solution, that works fine for me.

同样的方式你可以让它可见。这只是我的解决方案的片段,对我来说很好用。