[英]Setting text of element with JS ignores \n linebreak?
I want to set a the text of a paragraph element via JS.我想通过 JS 设置段落元素的文本。 The string contains line breaks (\n), but they are not visible in the paragraph .
该字符串包含换行符(\n),但它们在段落中不可见。
This is the desired result :这是期望的结果:
<p> Lorem ipsum dolor sit amet,<br> consetetur sadipscing elitr,<br> sed diam nonumy <br> eirmod tempor... </p>
This it how it looks when I set the text via JS :这是我通过 JS 设置文本时的样子:
document.getElementById("text").textContent = "Lorem ipsum dolor sit amet,\n" + "consetetur sadipscing elitr,\n" + "sed diam nonumy \n eirmod tempor...";
<p id="text"></p>
How can I achieve the behaviour of the first example with JS?我怎样才能用JS实现第一个例子的行为?
From the MDN documentation for HTMLElement.innerText
:来自
HTMLElement.innerText
的 MDN 文档:
Note:
innerText
is easily confused withNode.textContent
, but there are important differences between the two.注意:
innerText
很容易与Node.textContent
混淆,但两者之间有重要区别。 Basically,innerText
is aware of the rendered appearance of text, whiletextContent
is not.基本上,
innerText
知道文本的渲染外观,而textContent
则不知道。
So, if you use innerText
instead, you'll get the expected result:因此,如果您改为使用
innerText
,您将获得预期的结果:
document.getElementById("text").innerText = "Lorem ipsum dolor sit amet,\n" + "consetetur sadipscing elitr,\n" + "sed diam nonumy \n eirmod tempor...";
<p id="text"></p>
Don't reach for innerText
all the time: textContent
is more performant... but in some cases like this, innerText
is the right tool.不要一直使用
innerText
: textContent
的性能更高......但在某些情况下, innerText
是正确的工具。
You can try this too.你也可以试试这个。 Using insertAdjacentHTML
使用 insertAdjacentHTML
let innerElem = ` Lorem ipsum dolor sit amet,<br> consetetur sadipscing elitr,<br> sed diam nonumy <br> eirmod tempor...`; document.getElementById("text").insertAdjacentHTML("afterbegin",innerElem);
<p id="text"></p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.