getElementsByTagName().length 返回零
我正在尝试做一件简单的事情,例如:
var elements = document.getElementsByTagName("input");
console.log(elements);
console.log(elements.length);
console.log(elements) 显示包含 28 个输入元素的 NodeList,但 elements.length 始终为 0。
我也看到了这个 getElementsByTagName("div").length 对任何网页返回零 但是我不明白到底是什么发生这种情况的原因以及如何解决它。我还注意到 Firefox、IE、Chrome 上都会发生这种情况。
有人可以帮我吗?
I am trying to do a simple thing such as:
var elements = document.getElementsByTagName("input");
console.log(elements);
console.log(elements.length);
The console.log(elements) shows the NodeList containing 28 input elements, but the elements.length is always 0.
I've also seen this getElementsByTagName("div").length returns zero for any webpage however I didn't understand what exactly is the reason for it happening and how to fix it. I've also noticed that this happens on both Firefox, IE, Chrome.
Anyone could help me out?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
NodeList
是一个实时集合,非延迟脚本立即执行(请参阅脚本延迟)。尝试一下,您就会了解会发生什么:
NodeList
is a live collection and non-deferred scripts execute immediately (see script defer).Try this and you will get an idea of what happens:
发生这种情况是因为 JS 的异步行为。您试图在渲染之前显示元素的值。
为了避免这种情况,您可以将“async”属性添加到标记中,如下例所示:
This happens because of the asynchronous behaviour of JS. You're trying to display the element's value before it is being rendered.
In order to avoid it, you could add the "async" attribute to your tag, as in the following example:
您的脚本应该具有“deter”属性来检测标签
your script should have the attribute "deter" to detect the tags