问题描述
如果我从一个元素中获取一些html,然后尝试将其分配为另一个元素的文本内容,则保留新行 not (至少不在最新的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))});
下面是一个正在运行的示例:
应该有一些方法来设置一个html元素作为另一个文本,同时正确保留换行符。
这是可能的text还是textContent?有没有其他方法可以做到这一点?有一个简单的解决方法吗?一个不简单的解决方法?
正如您已经确定的,Web浏览器通常不会呈现换行符 \\\
作为换行符。如果您拒绝添加换行符元素,请,您可以使用 CSS属性的值为
pre-line
,它将:
请务必在使用前检查属性的兼容性表。
< div style =white- space:pre-line;>
在
处查看
这些换行符!
< / div>
If I grab some html from one element, then attempt to assign it as the text content of another element, newlines are not preserved (at least not in the latest Firefox and Chromium).
So, for example, the follow code (with sensible html) produces output where the newlines are replaced by spaces. Well, except the alert, which works as expected.
$("#info").data("html", $("#info").html());
$("#jquery").text($("#info").data("html"));
document.getElementById("javascript").textContent = $("#info").data("html");
$("#alert").click(function() { alert($("#info").data("html")) });
Here's a running example: http://jsfiddle.net/76S7z/2/
There should be some method of setting the html of one element as the text of another while preserving newlines properly.
Is this possible with "text" or "textContent"? Is there an alternative way to do this? Is there a simple workaround? A less than simple workaround?
As you've already determined, Web browsers don't normally render newline characters \n
as line breaks. If you're resistent to adding the line break element <br />
, you can use the white-space
CSS property with the value pre-line
, which will:
Be sure to check the property's compatibility tables before using.
<div style="white-space: pre-line;">
Look
at
these line breaks!
</div>
这篇关于在使用“.text”时保留换行符或“.textContent”。可能?备择方案?解决方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!