我对javascript innerText property感到困惑。它究竟是如何工作的?
let h1 = document.querySelector('h1');
console.log('Confused', h1);
let h11 = document.querySelector('h1');
console.log('Confused', h11);
h1.innerText = 'Inserted';
console.log('Got it', h1);
我可以理解 h1 和- h2 都包含相同的节点,为什么在 h1 节点中插入文本会导致 h1 和 h11 发生变化。
- 但我不明白为什么这个 h1 和 h11 都插入第 2 行和第 4 行(Markdown 在控制台内混淆(。虽然我在代码末尾插入了?
我认为要了解正在发生的事情,您可以使用此插图 在控制台中运行此代码段
let h1 = document.querySelector('h1');
console.log('Confused', h1);
let h11 = document.querySelector('h1');
console.log('Confused', h11);
console.log('Got it', h1);
这是没有h1.innerText = 'Inserted';
并观察h1
和h11
的值。
然后运行这个
h1.innerText = 'Inserted';
并在控制台中再次观察h1
和h11
的值。您将意识到它们已更新为相同的东西,innerText
要Inserted
。
现在运行这个
let h1 = document.querySelector('h1');
console.log('Confused', h1);
let h11 = document.querySelector('h1');
console.log('Confused', h11);
h1.innerText = 'Inserted';
console.log('Got it', h1);
观察最终结果是运行h1.innerText = 'Inserted';
后得到的结果 现在发生了什么?JavaScript variables are containers for storing data values.
您会看到变量只是用于存储数据的容器。在h1.innerText = 'Inserted';
出现之前,他们有你期望他们拥有的内容,但是当这条线运行时,他们的内容会发生变化,你会得到你正在观察的内容。问题是这种情况发生得如此之快,以至于您看不到h1
和h11
的第一个版本,而只能看到它们的更新版本,因为实际上它们只是存储数据的容器,而不是数据本身,或者您可以将它们称为the name of a storage location