jQuery 在字符串中使用换行符 (\n) 并在 HTML 中呈现相同的内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8573890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using new line(\n) in string and rendering the same in HTML
提问by KeenUser
I have a string say
我有一个字符串说
string display_txt = "1st line text" +"\n" + "2nd line text";
in Jquery, I am trying to use
在 Jquery 中,我正在尝试使用
('#somediv').html(display_txt).css("color", "green")
quite clearly I am expecting my msg to be displayed in 2 lines, but instead \n is being displayed in the message. Any quick fixes for that?
很明显,我希望我的 msg 显示在 2 行中,但是 \n 显示在消息中。有什么快速解决办法吗?
Thanks,
谢谢,
采纳答案by Samich
Use <br />
for new line in html:
使用<br />
在HTML新行:
display_txt = display_txt.replace(/\n/g, "<br />");
回答by vsync
Set your css in the table cell to
将表格单元格中的 css 设置为
white-space:pre-wrap;
document.body.innerHTML = 'First line\nSecond line\nThird line';
body{ white-space:pre-wrap; }
回答by Frank im Wald
You could use a pre tag instead of a div. This would automatically display your \n's in the correct way.
您可以使用 pre 标签而不是 div。这将自动以正确的方式显示您的 \n。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
var display_txt = "1st line text" +"\n" + "2nd line text";
$('#somediv').html(display_txt).css("color", "green");
});
</script>
</head>
<body>
<pre>
<p id="somediv"></p>
</pre>
</body>
</html>
回答by Frank im Wald
Maybe .text
instead of .html
?
也许.text
而不是.html
?
回答by Kevin H Griffith
I had the following problem where I was fetching data from a database and wanted to display a string containing \n
. None of the solutions above worked for me and I finally came up with a solution: https://stackoverflow.com/a/61484190/7251208
我遇到了以下问题,我从数据库中获取数据并希望显示包含\n
. 以上解决方案都不适合我,我终于想出了一个解决方案:https: //stackoverflow.com/a/61484190/7251208