jQuery文本()和换行符

我想能够说

$(someElem).text('this\n has\n newlines); 

并在浏览器中使用换行符进行渲染。 我find的唯一的解决方法是将css属性“white-space”设置为someElem上的“pre”。 这几乎可以工作,但是在文本和someElem的顶部之间有一个令人讨厌的大填充,即使我将填充设置为0。是否有办法摆脱这种情况?

这是2015年。这个问题的正确答案是使用CSS white-space: pre-linewhite-space: pre-wrap 。 清洁和优雅。 IE支持的最低版本是8。

https://css-tricks.com/almanac/properties/w/whitespace/

PS直到CSS3成为常用,你可能需要手动修剪初始和/或尾随空白。

如果你把jQuery对象存储在一个variables中,你可以这样做:

 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> 

这是我使用的:

 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")); 

或者,尝试使用.html ,然后使用<pre>标记进行换行

 $(someElem).html('this\n has\n newlines').wrap('<pre />'); 

您可以使用html代替text并用<br>replace\n每个匹配项。 你将不得不正确地逃避你的文字。

 x = x.replace(/&/g, '&amp;') .replace(/>/g, '&gt;') .replace(/</g, '&lt;') .replace(/\n/g, '<br>'); 

我build议直接使用someElem元素,因为用.html()replace也会replacestring中的其他HTML标记。

这是我的function:

 function nl2br(el) { var lines = $(el).text().split(/\n/); $(el).empty(); for (var i = 0 ; i < lines.length ; i++) { if (i > 0) $(el).append('<br>'); $(el).append(document.createTextNode(lines[i])); } return el; } 

通过:

 someElem = nl2br(someElem); 

使用CSS空白属性可能是最好的解决scheme。 使用Firebug或Chrome开发者工具来确定您所看到的额外填充的来源。