Accessing a div using id without getElementById and jQuery
我相信在 JS 中访问具有 id 的元素的标准方法是使用 getElementById。如果人们喜欢使用 jQuery,那么他们可能会使用他们的选择器。但最近我遇到了一个非常简单的代码示例,如下所示:
HTML:
1
|
Hello
|
JS:
1
|
h.innerHTML =“Too bad”;
|
这是唯一的代码,没有其他变量声明,仅供大家了解。
我们如何能够访问 div 元素,就好像它是一个 Javascript 对象一样?
附言:代码示例有效。
- 这是一个不值得依赖的坏主意,因为名为 h 的全局变量将隐藏此属性并有效地隐藏它。
- 另请参阅具有 ids 的 DOM 树元素是否成为全局变量?。 AFAIK 它已经标准化了。
How are we able to access the div element as if it is a Javascript
object?
ids 默认创建为全局对象的属性(在全局上下文中)。
如果你这样做 Hello 它将创建一个 h22
的全局变量
根据规范,
Otherwise return an HTMLCollection rooted at the Document node, whose
filter matches only named objects with the name name. (By definition,
these will all be elements.)HTML elements that have an id content attribute whose value is name.
所以 window 可以按照规范中给出的顺序确定从哪里选择值。
- 你能详细说明一下吗?
- 它们被创建为全局对象的 properties,与 global variables. 略有不同。特别是,创建同名的全局变量会隐藏底层属性。
- @VishalSubramanyamRajesh 上面解释过
- 谢谢@gurvinder372
参考 JavaScript 权威指南:
If you name an element in your HTML document using the id attribute, and if the
Window object does not already have a property by that name, the Window object is
given a nonenumerable property whose name is the value of the id attribute and whose name is the HTMLElement object that represents that document element.Window object serves as the global object at the top of the scope chain in client-side JavaScript, so this means that the id attributes you use in your HTML documents become global variables accessible to your scripts. If your document includes the element
但也有一些例外。如果 window 对象已经有一个属性,该属性的名称也用作 html 文档中的 id 属性,则它将不能用作 window 对象的属性。
其次,如果您有一个可用作窗口属性的 id,并且我们也声明了一个具有相同名称的变量,那么我们显式创建的变量将覆盖包含 id 的窗口属性。
为了实际演示上述答案…
HTML:
1
|
<p>bar</p>
|
Javascript:
1
2 |
alert(window.foo);
console.log(window.foo.innerHTML); |
警报:
1
|
[object HTMLDivElement]
|
控制台:
1
|
<p>bar</p>
|
来源:https://www.codenong.com/37224092/