gpt4 book ai didi

javascript - innerText vs innerHTML vs label vs text vs textContent vs outerText

转载 作者:IT王子 更新时间:2023-10-29 02:40:35 28 4
gpt4 key购买 nike

我有一个由 Javascript 填充的下拉列表。

在决定加载时显示的默认值时,我意识到以下属性显示的值完全相同:

  • innerText
  • innerHTML
  • label
  • text
  • textContent
  • outerText

我自己的研究显示了基准测试或其中一些(但不是全部)之间的比较。

我可以根据自己的常识选择 1 或另一个,因为它们提供相同的结果,但是,我担心如果数据发生变化,这不是一个好主意。

我的发现是:

  • innerText将按原样显示值并忽略可能包含的任何 HTML 格式
  • innerHTML将显示值并应用任何 HTML 格式
  • label似乎与 innerText 相同, 所以我看不出区别
  • text似乎与 innerText 相同但 jQuery 速记版本
  • textContent看起来与 innerText 相同但保留格式(例如 \n )
  • outerText似乎与 innerText 相同

我的研究只能带我走这么远,因为我只能测试我能想到的或阅读已发表的内容,但任何人都可以确认我的研究是否正确以及 label 是否有任何特别之处|和 outerText

最佳答案

来自 MDN :

Internet Explorer introduced element.innerText. The intention is pretty much the same [as textContent] with a couple of differences:

  • Note that while textContent gets the content of all elements, including <script> and <style> elements, the mostly equivalent IE-specific property, innerText, does not.

  • innerText is also 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.

所以 innerText将不包括被 CSS 隐藏的文本,但 textContent会的。

innerHTML returns the HTML as its name indicates. Quite often, in order to retrieve or write text within an element, people use innerHTML. textContent should be used instead. Because the text is not parsed as HTML, it's likely to have better performance. Moreover, this avoids an XSS attack vector.

如果您错过了,让我再重复一遍:不要使用.innerHTML除非您特别打算在元素中插入 HTML 并已采取必要的预防措施以确保您插入的 HTML 不包含恶意内容。如果只想插入文本,请使用 .textContent或者,如果您需要支持 IE8 及更早版本,请使用功能检测在 .textContent 之间切换和 .innerText .

有这么多不同属性的一个主要原因是不同的浏览器最初对这些属性有不同的名称,并且仍然没有对所有这些属性的完整的跨浏览器支持。如果你正在使用 jQuery,你应该坚持 .text()因为这是为了消除跨浏览器的差异而设计的。*

对于其他一些:outerHTMLinnerHTML基本相同, 除了它包含它所属元素的开始和结束标记。我似乎找不到关于 outerText 的太多描述根本。我认为这可能是一个模糊的遗留属性,应该避免。

关于javascript - innerText vs innerHTML vs label vs text vs textContent vs outerText,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24427621/

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