Javascript jQuery text() 和换行符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4535888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:48:50  来源:igfitidea点击:

jQuery text() and newlines

javascriptjqueryhtml

提问by Joe Armstrong

I want to be able to say

我想说

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

and it renders with newlines in the browser. The only workaround I have found is to set the css property 'white-space' to 'pre' on someElem. This almost works, but then I have an annoyingly large padding between the text and the top of someElem, even when I set padding to 0. Is there a way to get rid of this?

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

回答by cleong

It's the year 2015. The correct answer to this question at this point is to use CSS white-space: pre-lineor white-space: pre-wrap. Clean and elegant. The lowest version of IE that supports the pair is 8.

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

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

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

P.S. Until CSS3 become commonyou'd probably need to manually trim off initial and/or trailing white-spaces.

PS在 CSS3 变得普遍之前,您可能需要手动修剪初始和/或尾随空格。

回答by José Roberto Araújo Júnior

If you store the jQuery object in a variable you can do this:

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

If you prefer, you can also create a function to do this with a simple call, just like jQuery.text() does:

如果您愿意,您还可以创建一个函数来通过简单的调用来执行此操作,就像 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>

回答by Peter V. M?rch

Here is what I use:

这是我使用的:

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

回答by karim79

Alternatively, try using .htmland then wrapwith <pre>tags:

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

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

回答by Mark Byers

You can use htmlinstead of textand replace each occurrence of \nwith <br>. You will have to correctly escape your text though.

您可以使用 html代替text和替换每次出现的\nwith <br>。不过,您必须正确转义您的文本。

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

回答by JochenJung

I would suggest to work with the someElemelement directly, as replacements with .html()would replace other HTML tags within the string as well.

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

Here is my 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;
}

Call it by:

通过以下方式调用它:

someElem = nl2br(someElem);

回答by daCoda

Try this:

尝试这个:

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

回答by Andrew B.

Using the CSS white-space property is probably the best solution. Use Firebug or Chrome Developer Tools to identify the source of the extra padding you were seeing.

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