简体   繁体   English

用 JS 设置元素的文本会忽略 \n 换行符?

[英]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 with Node.textContent , but there are important differences between the two.注意: innerText很容易与Node.textContent混淆,但两者之间有重要区别。 Basically, innerText is aware of the rendered appearance of text, while textContent 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.不要一直使用innerTexttextContent的性能更高......但在某些情况下, 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM