gpt4 book ai didi

javascript - 更新
 标签的内容时如何考虑换行?

转载 作者:行者123 更新时间:2023-11-28 17:55:42 25 4
gpt4 key购买 nike

看到this answer后我试图找到一种方法来更新 <pre> 的内容标记并使用隐式换行符(即在字符串文字中)显示换行符。我尝试设置各种属性:innerHTMLinnerTexttextContentnodeValue(在检查 this question 的答案后)但似乎没有一个保留了空白。

我知道我可以使用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>

如果您希望两者将字符串分成多行并且在字符串中包含换行符,则需要两者:

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

关于javascript - 更新 <pre> 标签的内容时如何考虑换行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44504589/

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