虽然听起来很傻,但我仍然没有找到合适的答案。
假设我想动态创建一个新的 DOM 元素并填充它的 textContent/innerText
使用 JS 字符串文字。
字符串太长了,我想把它分成三 block :
var h1 = document.createElement("h1");
h1.textContent = "This is a very long string and I would like to insert a carriage return HERE...
moreover, I would like to insert another carriage return HERE...
so this text will display in a new line";
问题是,如果我写
h1.textContent = "...I would like to insert a carriage return here... \n";
它不起作用,可能是因为浏览器认为 '\n' 是纯文本并按原样显示它(\r 也不起作用)。
另一方面,我可以更改 h1.innerHTML 而不是 textContent 并编写:
h1.innerHTML = "...I would like to insert a carriage return here...<br />";
这里
可以完成这项工作,但这样做不仅会替换文本内容,还会替换我的 h1 的所有 HTML 内容,这不是我想要的 .
有没有一种简单的方法可以解决我的问题?
我不会为了让文本位于不同的行而创建多个 block 元素。
任何想法将不胜感激。
提前致谢。
最佳答案
我知道这个问题很久以前就发布了。
几天前我遇到了类似的问题,以 json
格式从 Web 服务传递值并将其放入 table
cell
contentText
.
因为value是按格式传递的,比如"text row1\r\ntext row2"
等等。
对于 textContent
中的新行,您必须使用 \r\n
最后,我不得不使用 css white-space: pre-line;
(文本将在必要时换行,并在换行符处换行)一切正常。
或者,您可以仅使用 white-space: pre;
,然后文本将仅在换行符处换行(在本例中为 \r\n
)。
因此,有一个示例如何通过仅在换行符处换行来解决它:
var h1 = document.createElement("h1");
//setting this css style solving problem with new line in textContent
h1.setAttribute('style', 'white-space: pre;');
//add \r\n in text everywhere You want for line-break (new line)
h1.textContent = "This is a very long string and I would like to insert a carriage return \r\n...";
h1.textContent += "moreover, I would like to insert another carriage return \r\n...";
h1.textContent += "so this text will display in a new line";
document.body.appendChild(h1);
关于javascript - 如何将换行符/回车符插入到 element.textContent 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9980416/