javascript 使用 jquery .text() 方法向文本字符串添加新行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6577201/
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-10-25 21:09:18  来源:igfitidea点击:

Adding a new line to text string with jquery .text() method

javascriptjqueryhtml

提问by mowwwalker

When I do:

当我做:

function testtext()
{
    var text = "test line 1\n\
    test line 2"
    ;
    $("#divtext").text(text);   
}

It all appears on one line. When I do:

这一切都出现在一行上。当我做:

function testtext()
{
    var text = "test line 1\n\
    test line 2"
    ;
    document.getElementById("divtext").innerText = text;    
}

It works fine...

它工作正常...

采纳答案by user113716

If you're wondering why, it's because jQuery creates a new text nodeusing document.createTextNode, passing your string as the argument.

如果你想知道为什么,这是因为jQuery创建一个新的文本节点使用document.createTextNode,通过你的字符串作为参数。

This apparently behaves differently than innerText, though it seems to behave the same as setting .textContentand as explicitly setting the value of a textNode through .nodeValueor .data.

这显然与 的行为不同innerText,尽管它的行为似乎与设置.textContent和通过.nodeValue或显式设置 textNode 的值相同.data

回答by Sukesh Chand

Use $("#divtext").html(text);

利用 $("#divtext").html(text);

Instead of $("#divtext").text(text);

代替 $("#divtext").text(text);

回答by joseph

The text() method will do an HTML escape. There are some workarounds on the API page, but perhaps the text() method isn't best suited for what you want to do?

text() 方法将执行 HTML 转义。API 页面上有一些解决方法,但也许 text() 方法并不最适合您想要做的事情?

http://api.jquery.com/text/

http://api.jquery.com/text/