【问题标题】:Confused with javascript innerText property与 javascript innerText 属性混淆
【发布时间】:2023-11-12 08:26:01
【问题描述】:

我对 javascript innerText 属性感到困惑。它究竟是如何工作的?

  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 在控制台中被混淆了)。虽然我在代码末尾插入了?

【问题讨论】:

  • 感谢您的回答。但这不是我的问题。我的问题是我不明白为什么这个 h1 和 h11 都被插入到第 2 行和第 4 行(Markdown 在控制台内混淆)。虽然我在代码末尾插入了?
  • 啊,是的,我很抱歉。我误解了你的问题。
  • 从外观上看,至少在 Google Chrome 的实现中,console.log 被调用和执行之间似乎存在时间延迟。当我在超时(0 毫秒)内包装控制台日志时,我仍然得到“插入”。当我将超时设置为 50 毫秒时,它显示了原始的 h1。此外,当我使用 Chrome 的调试器一次执行每一行时,只有最后一个 console.log 显示“Inserted”
  • innerText 不是 javascript 属性,它是 HTMLElement 对象属性
  • console.log 中对象的输出不是静态的 - 当您检查内容时会对其进行评估...

标签: javascript html innertext


【解决方案1】:

我认为要了解正在发生的事情,您可以使用此插图 在控制台中运行这个 sn-p

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'; 并观察h1h11 的值。

然后运行这个

h1.innerText = 'Inserted';

并在控制台中再次观察h1h11 的值。您会意识到它们已经更新为与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'; 出现之前,他们拥有您期望他们拥有的内容,但是当该行运行时,他们的内容会发生变化,您会得到您所观察到的内容。问题是这种情况发生得如此之快,以至于您看不到h1h11 的第一个版本,而只能看到它们的更新版本,因为实际上它们只是用于存储数据而不是数据本身的容器,或者您可以将他们称为the name of a storage location

【讨论】: