更新 <pre> 标签的内容时如何遵守新行?

How can new line be respected when updating content of a <pre> tag?

看过 this answer I was trying to find a way to update the contents of a <pre> tag and have the new-lines displayed using implicit new-lines (i.e. in the string literal). I tried setting various properties: innerHTML, innerText, textContent, nodeValue (after checking answers to this question) 之后 none 似乎保留了白色-space。

我知道我可以使用 String.fromCharCode() - 例如"Bob " + String.fromCharCode(10, 13) + "is "...但也想找到一种使用前一种语法的方法。

//Perfectly valid code
var foo = "Bob \
is \
cool.";
document.addEventListener('DOMContentLoaded', function() {
  document.getElementById('pre').textContent = foo;
});
<pre id="pre"></pre>

有没有办法根据需要更新内容?

您似乎误解了链接到的答案。答案是:

If you wish to have a string which spans multiple lines, you may insert a backslash character '\' just before you terminate the line, like so:

//Perfectly valid code
var foo = "Bob \
is \
cool.";

However that string will not contain \n characters in the positions where the string was broken into separate lines. The only way to insert a newline into a string is to insert a character with a value of 10, the easiest way of which is the \n escape character.

var foo = "Bob\nis\ncool.";

所以这就是你应该做的:

//Perfectly valid code
var foo = "Bob\nis\ncool.";
document.addEventListener('DOMContentLoaded', function() {
  document.getElementById('pre').textContent = foo;
});
<pre id="pre"></pre>

如果你想 both 将字符串分成多行 在字符串中有换行符,你需要两者:

//Perfectly valid code
var foo = "Bob\n\
is\n\
cool.";
document.addEventListener('DOMContentLoaded', function() {
  document.getElementById('pre').textContent = foo;
});
<pre id="pre"></pre>

另一种方法是使用 template literals.

// template literal syntax
var foo = `Bob 
is 
cool.`;
document.addEventListener('DOMContentLoaded', function() {
  document.getElementById('pre').textContent = foo;
});
<pre id="pre"></pre>