如何使用 jquery 获取动态创建的没有 Id 的子元素的高度

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

How do I use jquery to get the height of a dynamically created child element with no Id

jqueryhtmlheight

提问by Carter

I have a div that dynamically get's loaded with two images always and possibly one div in between. Neither the images or the div have id's associated with them (and I can't make them have Id's). Inspecting them with firebug they are just shown as <IMG>and <DIV>. I need to get the height of this child div when it exists.

我有一个 div,它总是动态加载两个图像,中间可能还有一个 div。图像或 div 都没有与它们关联的 ID(我不能让它们有 ID)。用萤火虫检查它们,它们只是显示为<IMG><DIV>。当它存在时,我需要获取这个子 div 的高度。

I was hoping I could do something like this...

我希望我能做这样的事情......

$("#parentDiv > DIV").height();

or this...

或这个...

$("#parentDiv > DIV")[0].height();

Since jquery $ returns an array. The second one gives javascript errors so I know I'm off there. I think these should be close though. Any ideas?

由于 jquery $ 返回一个数组。第二个给出了 javascript 错误,所以我知道我不在那里。我认为这些应该很接近。有任何想法吗?

Edit:Here is the html I am running against.

编辑:这是我正在运行的 html。

<DIV id="parentDiv" name="parentDiv">
    <IMG style="DISPLAY: block; VERTICAL-ALIGN: bottom; CURSOR: pointer" height="17" src="..." />

    <!-- this div may or may not be here -->
    <DIV style="DISPLAY: block; BACKGROUND-IMAGE: url(...); WIDTH: 16px; CURSOR: pointer; BACKGROUND-REPEAT: repeat-y; POSITION: relative; HEIGHT: 144px; outline: none">
        <DIV style="LEFT: 0px; OVERFLOW: hidden; WIDTH: 16px; POSITION: absolute; TOP: 128px; HEIGHT: 8px">
             <IMG style="LEFT: 0px; POSITION: absolute; TOP: 0px" height="8" src="..." />
        </DIV>
    </DIV>

    <IMG style="DISPLAY: block; VERTICAL-ALIGN: bottom; CURSOR: pointer" height="17" src="..." />
</DIV>

回答by cobbal

to get an indexed jQuery element, use the eq()function:

要获取索引的 jQuery 元素,请使用以下eq()函数:

$("#parentDiv > DIV").eq(0).height();

or

或者

$($("#parentDiv > DIV")[0]).height();

or

或者

$("#parentDiv > DIV:eq(0)").height();

回答by Marius

Just to add to all the other ways of doing it:

只是添加到所有其他方法中:

$("#parentDiv > div:first").height();

回答by svinto

Your first one will work, as long as your selector is okay. Try the following and see what you get:

只要您的选择器没问题,您的第一个就可以工作。尝试以下操作,看看你会得到什么:

$("#parentDiv > DIV").css("background", "pink");

If you don't get a pink background where you'd expect, fix your selector, and it'll work with the height-statement as well.

如果您没有得到您期望的粉红色背景,请修复您的选择器,它也可以与高度语句一起使用。

回答by michal kralik

Try

尝试

$($("#parentDiv > div")[0]).height();

That should do the trick

这应该够了吧