如何在 jQuery 中的 .text() 中显示新行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18071164/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:58:18  来源:igfitidea点击:

How do I display new line in .text() in jQuery?

javascriptjquerytextnewline

提问by User4678

I have the following code:

我有以下代码:

var stringDisplay = "Hello\nWorld";
$("#meaning").text(stringDisplay);

It is displaying \ninstead of a newline.

它显示\n而不是换行符。

The output is showing up as Hello\nWorld.

输出显示为Hello\nWorld.

I used <br>tag also in place of \n, but it's still not working.

<br>也用tag 代替了\n,但它仍然不起作用。

回答by Blender

You will have to use both .html()and replace the newline:

您必须同时使用两者.html()并替换换行符:

var escaped = $('<div>').text(stringDisplay).text();
$('#meaning').html(escaped.replace(/\n/g, '<br />'));

An alternative would be to style the element:

另一种方法是设置元素的样式:

white-space: pre-wrap;

回答by Mr Vinh

How about this

这个怎么样

$('meaning').html('line1<br>line2');