Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/448.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用jquery.text()方法向文本字符串添加新行_Javascript_Jquery_Html - Fatal编程技术网

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

Javascript 使用jquery.text()方法向文本字符串添加新行,javascript,jquery,html,Javascript,Jquery,Html,当我这样做时: function testtext() { var text = "test line 1\n\ test line 2" ; $("#divtext").text(text); } function testtext() { var text = "test line 1\n\ test line 2" ; document.getElementById("divtext").innerText = tex

当我这样做时:

function testtext()
{
    var text = "test line 1\n\
    test line 2"
    ;
    $("#divtext").text(text);   
}
function testtext()
{
    var text = "test line 1\n\
    test line 2"
    ;
    document.getElementById("divtext").innerText = text;    
}
这一切都出现在一行上。当我这样做时:

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

它工作正常…

如果您想知道为什么,那是因为jQuery使用
document.createTextNode
,将字符串作为参数传递

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

text()方法将执行HTML转义。API页面上有一些变通方法,但是text()方法可能不适合您想要做的事情

使用
$(“#divtext”).html(文本)


而不是
$(“#divtext”)。text(text)

你的问题是什么??或者问题如果你设置
textContent
属性呢?好吧,HTML中的新行是使用

元素创建的,而不是“正常”的换行符。如果你有几分钟的时间,你能解释一下OP问了什么吗?@kobe:我几乎可以告诉你,OP想知道为什么会有不同。至少这是我在这件事上的想法。