jQuery text()和换行符

Joe*_*ong 107 html javascript jquery

我希望能够说出来

$(someElem).text('this\n has\n newlines);
Run Code Online (Sandbox Code Playgroud)

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

cle*_*ong 121

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

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

PS 直到CSS3变得普遍,您可能需要手动修剪初始和/或尾随空格.

  • 这篇文章有一个错误.这一年是2017年,而不是2015年.其他一切看起来都很准确. (6认同)
  • 这应该是答案. (3认同)
  • 这就是答案.应该更高.欢迎来到2016. (3认同)
  • 在2017年发现:仍然相关,仍然是问题的答案. (3认同)
  • 我有点困惑,这个答案如何让你“控制”中断发生的位置?这个答案不是简单地集成了换行吗?当OP说他们已经尝试过这个并且它没有达到他们想要的效果时,这怎么可能是答案呢? (2认同)

Jos*_*ior 54

如果将jQuery对象存储在变量中,则可以执行以下操作:

var obj = $("#example").text('this\n has\n newlines');
obj.html(obj.html().replace(/\n/g,'<br/>'));
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="example"></p>
Run Code Online (Sandbox Code Playgroud)

如果您愿意,还可以使用简单的调用创建一个函数来完成此操作,就像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');
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="example"></p>
Run Code Online (Sandbox Code Playgroud)


Pet*_*rch 37

这是我使用的:

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"));
Run Code Online (Sandbox Code Playgroud)


kar*_*m79 20

或者,尝试使用.html然后用标签包装<pre>:

$(someElem).html('this\n has\n newlines').wrap('<pre />');
Run Code Online (Sandbox Code Playgroud)


Mar*_*ers 12

您可以使用 html替代text和取代的每次出现\n<br>.你必须正确地逃避你的文字.

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

  • [否](http://jsfiddle.net/nqVsX/).```将被视为文本. (7认同)
  • 有些读这个答案的人可能不知道这有多危险.切勿将此解决方案与用户提供的文本一起使用 PeterMørch的解决方案更可取. (7认同)