gpt4 book ai didi

javascript - 为什么.textContent 会在文档正文中添加意想不到的内容

转载 作者:行者123 更新时间:2023-11-30 08:38:15 28 4
gpt4 key购买 nike

我最近在玩耍,注意到一些涉及 .textContent 的奇怪行为属性(property)。

// I understand that .innerHTML should be used here.
document.body.textContent += 'string<br />';
document.body.textContent += 'string<br />';

我的问题不是如何防止这种情况发生,问题是:是什么导致代码被添加到文档主体,为什么这种情况只发生在第一个 .textContent而不是第二个?

另请注意 string<br />正在添加到正文中。

其他好奇心:这种行为在 firefox 和 chrome 中都可以重现,在代码片段和普通网页中都是如此,但在 FIDDLE 中却没有。

最佳答案

您的脚本通过堆栈片段放置在正文中。

那个script元素包含一些隐藏的文本内容(您的脚本的代码)。

然而,textContent无论如何包括它。如果您使用非标准 IE 的 innerText ,那不会发生。

根据 MDN ,

Differences from innerText

Internet Explorer introduced element.innerText. The intention is similar but with the following differences:

  • While textContent gets the content of all elements, including <script> and <style> elements, the IE-specific property innerText does not.
  • innerText is aware of style and will not return the text of hidden elements, whereas textContent will.
  • As innerText is aware of CSS styling, it will trigger a reflow, whereas textContent will not.

关于javascript - 为什么.textContent 会在文档正文中添加意想不到的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29436653/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com