使用纯 JavaScript 创建对此 HTML 元素的引用的最有效方法是什么?
如果我有以下 HTML:
<div id="container">
<iframe></iframe>
</div>
创建对
var element = document.getElementById('container').getElementsByTagName('iframe')[0];
IIRC,但是 getElementsByTagName 的执行速度可能很慢。这不是问题吗,因为
中只有一个元素?反正?
是否有更简洁和/或性能更好的方法来获取
If I have the following HTML:
<div id="container">
<iframe></iframe>
</div>
What is the most effective way (mainly in terms of performance) to create a reference to the <iframe> DOM element? I'm using something like the following:
var element = document.getElementById('container').getElementsByTagName('iframe')[0];
IIRC, though, getElementsByTagName can be a slow performer. Is that not an issue since there's only one element within the <div id="container"> anyway?
Is there a more concise, and/or better-performing way to get the <iframe> here? It's safe to say that it will always be the only child of <div id="container">, but not always the only <iframe> on the page.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 iframe 上放置一个 ID 并使用
gEBI
引用它。如果您没有注意到gEBTN
有任何延迟,那么我建议保持代码不变,是的,为gEBTN
提供上下文会有所帮助。Put an ID on the iframe and reference it with
gEBI
. If you're not noticing any latency withgEBTN
then I suggest keeping the code the same as is, and yes providing a context forgEBTN
helps.在这种情况下,您不会注意到性能。但是,如果您执行
document.getElementsByTagName
您可能会注意到它,因为它必须遍历整个 DOM 树。请记住,这并不总是与性能有关,在许多情况下,拥有清晰可读的代码比使用 Perl-one-liner 更好,因为当他们重新访问时,它对任何人(包括您)来说都看起来像是胡言乱语。 2周后。
如果您可以将
id
属性添加到iframe
元素,这当然是 Meder 所说的最佳解决方案。In this case you wont notice the performance. If you would however do
document.getElementsByTagName
you would probably notice it as it has to walk the entire DOM tree.Remember that it´s not always about performance, in many cases it´s better to have clear readable code then a perl-one-liner that will look like jibberish to anyone, including you, when they revisit it after 2 weeks.
If you can add an
id
attribute to theiframe
element that would of course be the best solution as Meder says.嗯,看来代码没问题。我认为您可以忘记如此简单的 JavaScript 代码的性能。
Hmm it seems it is all right with code. I think you can forget about performance for such simple javascript code.