没有 id 或 name 属性的元素的 innerHTML
为什么如果没有为锚元素指定 id 或 name 属性,以下代码无法工作?
<html>
<body>
<a href="#">First link</a>
<p>innerHTML of the first anchor:
<script>document.write(document.anchors[0].innerHTML);</script>
</p>
</body>
</html>
但是,如果我添加一个 id(或名称)属性,如下所示:
<a id="first" href="#">First link</a>
它开始工作。
为什么 id 或 name 属性如此重要?我没有在我的 javascript 代码中引用它。我不使用“getElementById”或任何东西,但它仍然需要指定一个 id。
PS 我只在 IE7 中进行了测试(不是最好的浏览器,但我目前无法访问任何更好的浏览器,并且它不能阻止我学习:)
更新:
感谢 Raynos 给了我 HTMLCollection 的想法他的回答是,通过搜索网络,我对这里发生的事情有了更深入的了解。
当我们使用 document.anchors
集合时,我们实际上是指带有 name
属性的 a
元素集合,该属性构成 元素充当锚点,而不是(仅)充当链接。
如果我们想要将 a
元素引用为链接,则不必指定 name
属性。在这种情况下,我们只需要使用 HTMLCollection 对象的不同实例,即 document.links
。
因此,如果我们将原始代码修改为:
document.write(document.links[0].innerHTML);
多么好的开悟的感觉啊! :)
Why is the following code NOT working without id or name attribute specified for the anchor element?
<html>
<body>
<a href="#">First link</a>
<p>innerHTML of the first anchor:
<script>document.write(document.anchors[0].innerHTML);</script>
</p>
</body>
</html>
But if I add an id (or name) attribute, like that:
<a id="first" href="#">First link</a>
It starts to work.
Why is id or name attribute so important? I don't refer to it in my javascript code. I don't use "getElementById" or anything, but it still wants an id to be specified.
P.S. I tested only in IE7 (not the best browser, but I don't have access to anything better at the moment, and it can't stop me from learning :)
UPDATE:
Thanks to Raynos who gave me an idea of HTMLCollection in his answer, I've gotten a deeper understanding of what's going on here, by searching the web.
When we use document.anchors
collection, we're actually referring to a collection of a
elements with the name
attribute that makes an a
element behave as an anchor, and not (only) as a link.
We don't have to specify the name
attribute if we want to refer to a
elements as links. In this case we just need to use a different instance of HTMLCollection object which is document.links
.
So the original code will work without name attribute if we modify it to:
document.write(document.links[0].innerHTML);
What a nice feeling of enlightenment! :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
WHATWG 说:
document.anchors
集合需要带有name
属性的元素。
众所周知,IE 存在将 id 和 name 视为“相同”事物的错误。因此,这可能可以解释为什么它适用于具有
id
属性的元素。
顺便说一句,
document.write
和.innerHTML
是邪恶的。WHATWG says:
the
document.anchors
collection needs<a>
elements with aname
attribute.IE is known to have bugs where it treats id's and name's as the "same" thing. So that would probably explain why it works for
<a>
elements with anid
attribute.As an aside,
document.write
and.innerHTML
are evil.你为什么不使用这个:
Why don't you use this: