虽然听起来很傻,但我还是没有找到合适的答案。
假设我想动态创建一个新的 DOM 元素并填充其 textContent/innerText
带有一个 JS 字符串文字。
这个字符串太长了,我想把它分成三块:
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 />";
在这里,< br/> 可以完成这项工作,但是这样做不仅可以替换文本内容,还可以替换 h1,这不是我想要的 中的所有 HTML 内容。
有什么简单的方法能解决我的问题吗?< br/> 我不会仅仅为了将文本放在不同的行上而创建多个块元素。
任何想法我都会非常感激。
先谢谢你。