在 jQuery 中,如何选择隐藏元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/679958/
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-26 09:34:10  来源:igfitidea点击:

In jQuery, how can I select a hidden element?

jquerycsscss-selectors

提问by Kirk

How can I select the <span>where displayis set to nonein the below code?

如何选择以下代码中设置的<span>位置?displaynone

<p id="p1">
<span id="test1" style="display:none">test1</span> 
<span id="test2" >test2</span> 
</p>

I can select the <span>whose ID is "test1" by using $("span[id='test1']"), but it does not work when I use $("span[style='display:none']").

我可以使用 选择<span>ID 为“test1”的对象$("span[id='test1']"),但使用时它不起作用$("span[style='display:none']")

Is there any method to get this element at a time?

有没有什么方法可以一次获取这个元素?

Thanks a lot.

非常感谢。

回答by Paolo Bergantino

You are looking for the :hiddenselector

您正在寻找:hidden选择器

Please note that the proper way of selecting an element by ID is simply:

请注意,通过 ID 选择元素的正确方法很简单:

$("#test1");

Doing it the way you are doing is making jQuery do unnecessary parsing and is much slower.

按照您的方式进行操作会使 jQuery 进行不必要的解析,而且速度要慢得多。

If you want to select #test1only if it is hidden, you do this:

如果您只想在#test1隐藏时选择,请执行以下操作:

$("#test1:hidden");

If you wanted to select all <span>elements that are hidden under #p1, you do this:

如果要选择<span>隐藏在 下的所有元素#p1,请执行以下操作:

$("span:hidden", "#p1");

As noted in the comments, the opposite of this selector is the :visibleselector:

如评论中所述,此选择器的反面是:visible选择器:

$("span:visible", "#p1");

Would then select any visible <span>elements in the element #p1.

然后将选择<span>元素中的任何可见元素#p1