jQuery text()和换行符

时间:2010-12-26 23:41:08

标签: javascript jquery html

我希望能够说出

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

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

9 个答案:

答案 0 :(得分:117)

这是2015年。此问题的正确答案是使用CSS white-space: pre-linewhite-space: pre-wrap。干净优雅。支持该对的IE的最低版本是8。

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

P.S。 直到CSS3变得普遍你可能需要手动修剪初始和/或尾随空格。

答案 1 :(得分:51)

如果将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>

答案 2 :(得分:36)

以下是我使用的内容:

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

答案 3 :(得分:18)

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

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

答案 4 :(得分:12)

您可以使用html代替text,并将每次\n替换为<br>。你必须正确地逃避你的文本。

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

答案 5 :(得分:1)

我建议直接使用someElem元素,因为.html()的替换也会替换字符串中的其他HTML标记。

这是我的功能:

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

答案 6 :(得分:0)

使用CSS white-space属性可能是最好的解决方案。使用Firebug或Chrome开发者工具来识别您看到的额外填充的来源。

答案 7 :(得分:0)

尝试一下:

$(someElem).html('this<br> has<br> newlines);

答案 8 :(得分:0)

对我来说,它在使用 jquerys .html() 函数而不是 .text() 函数时有效。 然后你可以添加
作为换行符。

var msg = someString + "<br/>" + anotherString;
$(elem).html(msg);