<分区>
如果我这样写 html:
<div id="foo">Foo<div>
window.foo
返回一个 dom 元素,window.document.getElementById("foo") === window.foo
返回 true
.
这是为什么呢?为什么每个人都使用 getElementById
?
旁注:为什么在 IE7/8 中禁止重写 window.foo
?如果我设置 window.foo = "bar"
会发生什么?
标签 javascript html dom
<分区>
如果我这样写 html:
<div id="foo">Foo<div>
window.foo
返回一个 dom 元素,window.document.getElementById("foo") === window.foo
返回 true
.
这是为什么呢?为什么每个人都使用 getElementById
?
旁注:为什么在 IE7/8 中禁止重写 window.foo
?如果我设置 window.foo = "bar"
会发生什么?
最佳答案
我不确定历史观点,但 HTML 5 specifies这些元素是作为属性直接暴露在 window
上的候选元素如果他们有 id
对象属性:
The Window interface supports named properties. The supported property names at any moment consist of the following, in tree order, ignoring later duplicates:
[...]
- the value of the id content attribute of any HTML element in the active document with a non-empty id content attribute.
这个定义的问题是它只保证如果有 <div id="foo">Foo<div>
然后window.foo
将被定义。它不保证它的值到底是什么(阅读规范以了解如何确定该值的规则;例如,it might return a collection)。
所以结果是“为什么要使用 getElementById
?”的答案。很简单:因为您可以依靠它返回您期望的内容,而无需考虑整个文档。
关于javascript - 为什么 dom 元素作为窗口对象的属性存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18713272/