如果我从一个元素中获取一些 html,然后尝试将其分配为另一个元素的文本内容,换行符不会保留(至少在最新的 Firefox 和 Chromium 中不会)。
因此,例如,以下代码(具有合理的 html)会生成换行符被空格替换的输出。好吧,除了警报,它按预期工作。
$("#info").data("html", $("#info").html());
$("#jquery").text($("#info").data("html"));
document.getElementById("javascript").textContent = $("#info").data("html");
$("#alert").click(function() { alert($("#info").data("html")) });
这是一个运行示例:http://jsfiddle.net/76S7z/2/
应该有一些方法可以将一个元素的 html 设置为另一个元素的文本,同时正确保留换行符。
“text”或“textContent”是否可行?有没有其他方法可以做到这一点?有简单的解决方法吗?一个不太简单的解决方法?
最佳答案
正如您已经确定的那样,Web 浏览器通常不会呈现换行符 \n
作为换行符。如果您拒绝添加换行符元素 <br />
, 您可以使用 white-space
值为 pre-line
的 CSS 属性,这将:
Sequences of whitespace are collapsed. Lines are broken at newline characters, at
<br>
, and as necessary to fill line boxes.
请务必在使用前检查属性的兼容性表。
<div style="white-space: pre-line;">
Look
at
these line breaks!
</div>
关于javascript - 使用 ".text"或 ".textContent"时保留换行符。可能的?备择方案?解决方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21033887/