HTML元素在JavaScript中作为全局变量表示,如何?(复制)

时间:2022-08-27 17:42:15

This question already has an answer here:

这个问题已经有了答案:

Does JavaScript represent each HTML element as a global variable which name is the id of the element ?

JavaScript是否将每个HTML元素表示为全局变量,元素的id是哪个名称?

Let's say I have a hidden input element like this:

假设我有一个像这样的隐藏输入元素:

<input type="hidden" value="10" id="myInput" />

so I can access it in JavaScript :

我可以用JavaScript访问:

console.log(myInput.value);

I tried it in chrome and firefox, and it worked for me.

我在chrome和火狐上试用过,它对我很有效。

My question is :

我的问题是:

  • Is this issue new in JavaScript ?
  • 这是JavaScript中的新问题吗?
  • Is it the best practice to get an element by id ?
  • 通过id获取元素是最佳实践吗?
  • Why they implement this functionality although using global variables is not the best practice?
  • 为什么他们实现这个功能,尽管使用全局变量不是最佳实践?

1 个解决方案

#1


4  

That is called as named access. Every element which has an id will be referenced in global scope. That is the window object. Even though it is not a good practice to use it, it is standardised with HTML5.

这被称为命名访问。具有id的每个元素都将在全局范围中引用。这就是窗口对象。尽管使用它并不是一个好的实践,但它已经被HTML5标准化了。

A simple conflicting case for its usage is,

使用它的一个简单的相互矛盾的例子是,

If you declare a variable in global scope like hide, and also you are having an element in your document with id hide. Then that element reference will be overridden by our global variable. At that time, if you use it(element reference) in any event handler or somewhere, it will results in error.

如果您在全局作用域中声明了一个变量,比如hide,并且您的文档中还有一个元素id hide。然后该元素引用将被全局变量覆盖。那时,如果您在任何事件处理程序或其他地方使用它(元素引用),它将导致错误。

#1


4  

That is called as named access. Every element which has an id will be referenced in global scope. That is the window object. Even though it is not a good practice to use it, it is standardised with HTML5.

这被称为命名访问。具有id的每个元素都将在全局范围中引用。这就是窗口对象。尽管使用它并不是一个好的实践,但它已经被HTML5标准化了。

A simple conflicting case for its usage is,

使用它的一个简单的相互矛盾的例子是,

If you declare a variable in global scope like hide, and also you are having an element in your document with id hide. Then that element reference will be overridden by our global variable. At that time, if you use it(element reference) in any event handler or somewhere, it will results in error.

如果您在全局作用域中声明了一个变量,比如hide,并且您的文档中还有一个元素id hide。然后该元素引用将被全局变量覆盖。那时,如果您在任何事件处理程序或其他地方使用它(元素引用),它将导致错误。