我想说的是
$(someElem).text('this\n has\n newlines);
并且它在浏览器中使用换行符呈现。我发现的唯一解决办法是在someElem上将css属性“空白”设置为“pre”。这几乎可以工作,但是我在文本和someElem顶部之间有一个恼人的大填充,即使我将padding值设置为0时也是如此。有没有办法摆脱这个?
发布于 2012-10-26 14:41:25
如果将jQuery对象存储在变量中,则可以执行以下操作:
var obj = $("#example").text('this\n has\n newlines');
obj.html(obj.html().replace(/\n/g,'<br/>'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="example"></p>
如果您愿意,也可以像jQuery.text()一样,通过简单的调用创建一个函数来完成此操作:
$.fn.multiline = function(text){
this.text(text);
this.html(this.html().replace(/\n/g,'<br/>'));
return this;
}
// Now you can do this:
$("#example").multiline('this\n has\n newlines');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="example"></p>
发布于 2011-06-23 22:38:23
下面是我使用的代码:
function htmlForTextWithEmbeddedNewlines(text) {
var htmls = [];
var lines = text.split(/\n/);
// The temporary <div/> is to perform HTML entity encoding reliably.
//
// document.createElement() is *much* faster than jQuery('<div></div>')
// http://stackoverflow.com/questions/268490/
//
// You don't need jQuery but then you need to struggle with browser
// differences in innerText/textContent yourself
var tmpDiv = jQuery(document.createElement('div'));
for (var i = 0 ; i < lines.length ; i++) {
htmls.push(tmpDiv.text(lines[i]).html());
}
return htmls.join("<br>");
}
jQuery('#div').html(htmlForTextWithEmbeddedNewlines("hello\nworld"));
发布于 2010-12-27 07:43:03
您可以使用html
而不是text
,并将每次出现的\n
替换为<br>
。不过,您必须正确转义您的文本。
x = x.replace(/&/g, '&')
.replace(/>/g, '>')
.replace(/</g, '<')
.replace(/\n/g, '<br>');
https://stackoverflow.com/questions/4535888
复制相似问题