当我将document.getElementById
存储在var
中时,我无法更改innerText
var status = document.getElementById('status');
// This doesn't work (nothing changes in the element)
function change() {
status.innerText = "Ready.";
}
但当我存储它在const
我可以。为什么?
const status = document.getElementById('status');
// This works
function change() {
status.innerText = "Ready.";
}
在顶层用var
声明的元素被赋值给全局对象。当您执行var status =
时,您将分配给window.status
-但window.status
是保留的,必须始终是字符串。因此,document.getElementById('status');
的结果在赋值时被转换为字符串。
用const
声明的变量,相反,在顶层时不会被赋值给全局对象,因此window.status
的问题就不会出现。
另一个解决方案是在IIFE中编写代码:
(() => {
var status = document.getElementById('status');
function change() {
status.innerText = "Ready.";
}
})();
或者使用与status
不同的变量名