转换 HTML 编码的 < br/ > 在 jquery .text() 中为 html 新行标记
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14426079/
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
Convert HTML-encoded < br/ > to html new line tag in jquery .text()
提问by user961627
I have some text in a variable sometext
which I want to assign to div
using $('div').text(sometext);
. The problem is that all <br/>
s in sometext
turn into < br/ >
. I cannot use $('div').html()
because there's a lot of internal structure that I want to retain within the div
, so I can only use the .text()
function.
我在一个变量中有一些文本sometext
,我想分配给div
using $('div').text(sometext);
。问题是所有的<br/>
s 都sometext
变成了< br/ >
. 我无法使用,$('div').html()
因为我想在 中保留很多内部结构div
,所以我只能使用该.text()
功能。
So once I've passed the text over the to the div
, is there any way to change the encoded <br/>
tag into a real line break in HTML? I mean something like this:
因此,一旦我将文本传递给div
,有没有办法将编码的<br/>
标签更改为HTML 中的真正换行符?我的意思是这样的:
$('div').convertMyBRsToHTML();
回答by axel.michel
Your requested function should look like this:
您请求的函数应如下所示:
$.fn.convertMyBRsToHTML = function(text){
this.text(text);
this.html(this.html().replace(/<br\s*\/>/g,'<br/>'));
return this;
}
Now you could use by:
现在您可以通过以下方式使用:
$(YOUR_SELECTOR).convertMyBRsToHTML("<b>Some</b> new text.<br />next line<br />and so on");
回答by SLaks
You can replace the <br>
s before setting the text:
您可以<br>
在设置文本之前替换s:
$('div').text(sometext.replace(/<br\s*\/?>/gi, '\n');