document.getElementById()中var和const的区别



当我将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不同的变量名