如何使用 jquery 查找 display=none 的元素并将元素 id 返回给变量?

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

How to use jquery to find the element with display=none and return the elements id to a variable?

jquery

提问by David

I am using jquery to to find the element on the page with display set to none and return it's id in a variable. My attempt is below:

我正在使用 jquery 来查找页面上显示设置为 none 的元素,并在变量中返回它的 id。我的尝试如下:

$(".galleryitem[display='none']").this

Can someone tell me where I am going wrong...

谁能告诉我我哪里错了...

回答by Vivek

I don't think that you need to add :hiddenpsuedo selector. The following will give you the id of selector irrespective of whether it is hidden or not.

我认为您不需要添加:hidden伪选择器。无论是否隐藏,以下内容都会为您提供选择器的 id。

var elementId = $(".galleryitem").attr("id");

but if you add it will be bit faster-

但如果你添加它会更快一点 -

var elementId = $(".galleryitem:hidden").attr("id");

回答by Vivek Goel

  $(".galleryitem:hidden").attr("id");

回答by Liviu Dragulin

Since jQuery 1.3.2, an element is visible if its browser-reported offsetWidth or offsetHeight is greater than 0. What does this change mean? It means that if your element's CSS display is “none”, or any of its parent/ancestor element's display is “none”, or if the element's width is 0 and the element's height is 0 then an element will be reported as hidden.

从 jQuery 1.3.2 开始,如果浏览器报告的 offsetWidth 或 offsetHeight 大于 0,则元素是可见的。这个变化意味着什么?这意味着如果您的元素的 CSS 显示为“none”,或者其任何父/祖先元素的显示为“none”,或者如果元素的宽度为 0 且元素的高度为 0,则元素将被报告为隐藏。

Example:

例子:

This means the .galleryitemelement is recognized as hidden only if the parrent has display: nonestyle:

这意味着.galleryitem元素仅在父级具有display: none样式时才被识别为隐藏:

var elementId = $(".parent .galleryitem:hidden").attr("id");

or

或者

var elementId = $(".galleryitem:hidden").attr("id");

You can choose the example that works best for you.

您可以选择最适合您的示例。

回答by Henry

var elementId = $(".galleryitem:hidden").attr("id");

回答by Mark Coleman

To find hidden elements you can use the :hiddenpsuedo selector.

要查找隐藏元素,您可以使用:hidden伪选择器。

$(".galleryitem:hidden").each(function(){
   //do something with each element.
});

Or if you only have one item you can simply do the following:

或者,如果您只有一项,您可以简单地执行以下操作:

var id = $(".galleryitem:hidden")[0].id

Example on jsfiddle

jsfiddle 示例