简体   繁体   English

element.children 的 console.log 显示长度为 0,但稍后展开时包含三个条目

[英]console.log of element.children shows 0 length but has three entries when expanded later

In my JavaScript, I have two elements.在我的 JavaScript 中,我有两个元素。

I have logged the two elements and it shows the following:我已经记录了这两个元素,它显示了以下内容:

Element 1:元素 1:

在此处输入图像描述

Element 2:要素 2:

在此处输入图像描述

The problem is:问题是:

  • When I console.log the children of each element ( element.children ) it obviously returns a list of elements.当我console.log每个元素( element.children )的孩子时,它显然会返回一个元素列表。
  • But the weird thing is, that one element is empty (and has a length of 0), but has 3 elements (and has a length of 3) once expanded.但奇怪的是,一个元素是空的(长度为 0),但一旦展开就有 3 个元素(长度为 3)。

If you read the logs below for the children of the elements, you will understand what I am talking about...如果您阅读以下元素子项的日志,您就会明白我在说什么......

Element 1 (this one is working as expected):元素 1(此元素按预期工作):

在此处输入图像描述

Element 2 (the problematic one):元素 2(有问题的元素):

在此处输入图像描述

Does anyone have any idea what is going on here?有谁知道这里发生了什么? How can there be contradictory reports of the number of children?孩子的数量怎么会有相互矛盾的报道?

How do I fix this?我该如何解决? I need to loop through the children, but it won't let me because the length is apparently 0.我需要遍历孩子,但它不会让我因为长度显然是 0。

Thanks in advance.提前致谢。 All help appreciated.所有帮助表示赞赏。

When you log objects to the console, the object's current state is not snapshotted and displayed (as you might expect);当您将对象记录到控制台时,对象的当前状态不会被快照和显示(如您所料); instead, the console gets a live reference to the object.相反,控制台会获得对该对象的实时引用 When you expand it in the console, you see its contents as of when you expand it , not as of when you logged it.在控制台中展开它时,您会看到展开时的内容,而不是登录时的内容。 More on that in this question and its answers .有关此问题及其答案的更多信息。

So apparently your collections are empty when you do your logging, and then gain their elements later.因此,当您进行日志记录时,显然您的集合是空的,然后再获取它们的元素。 You just want to make your code wait until the collections are populated.您只想让您的代码等到集合被填充。 For instance, if you're doing this immediately when your script is run, consider putting the script at the end of the document, right before the closing </body> tag.例如,如果您在脚本运行时立即执行此操作,请考虑将脚本放在文档末尾,就在结束</body>标记之前。

The very subtle blue (i) icon next to the object has a tooltip that's useful;对象旁边非常微妙的蓝色 (i) 图标有一个有用的工具提示; if you hover it you see:如果你悬停它,你会看到:

工具提示说“左侧的对象值在记录时被生成,下面的值刚刚被评估。”

It says "Object value at left was snapshotted when logged, value below was evaluated just now."它说“左侧的对象值在记录时被快照,下面的值刚刚被评估。”


But generally: Rather than stumbling around in the dark with a console.log torch, I suggest turning on the lights using the debugger built into your browser and/or IDE.但一般来说:我建议不要使用console.log手电筒在黑暗中磕磕绊绊,而是使用浏览器和/或 IDE 中内置的调试器打开灯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM