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

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

本文关键字:显示 新行 text jQuery      更新时间:2023-09-26

我有以下代码:

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

它显示的是'n而不是换行符。

输出显示为Hello'nWorld

我也使用了<br>标签来代替'n,但它仍然不起作用。

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

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

另一种选择是对元素进行样式化:

white-space: pre-wrap;

这个怎么样

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