javascript - 为什么 dom 元素作为窗口对象的属性存在?

标签 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/

相关文章:

javascript - 检查数组是否包含指定对象

css - div 的不当行为

html - 如何摆脱 jQuery Mobile Listview 缩略图下的空白

javascript - 通过 Javascript 设置上下文菜单属性

Javascript html dom元素数组for in循环

javascript - 如何在redux中修改对象属性?

javascript - jquery 文件未与 html 文件链接

javascript - 使用 jQuery 访问 javascript 对象

html - 试图做卫报的练习。我名为 "here"的链接不起作用。我尝试了各种调试,但无法解决

javascript - 如何通过选项值获取选择元素