假设我想动态创建一个新的 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 />";
这里的
可以完成这项工作,但这样做不仅会替换文本内容,还会替换我的 h1 的所有 HTML 内容,这不完全是我想要的.
有没有简单的方法可以解决我的问题?
我不会仅仅为了将文本放在不同的行上而创建多个块元素。
我知道这个问题很久以前就发布了。
几天前我遇到了类似的问题,从网络服务传递值json
格式化并放入table
cell
contentText
.
因为值是以格式传递的,例如,"text row1\r\ntext row2"
等等。
对于新行textContent
你必须使用\r\n
最后,我不得不使用 csswhite-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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)