最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Adding a new line to text string with jquery .text() method - Stack Overflow

programmeradmin0浏览0评论

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...

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...

Share Improve this question asked Jul 5, 2011 at 1:08 mowwwalkermowwwalker 17.4k30 gold badges108 silver badges164 bronze badges 3
  • 1 what is your question?? or issue – kobe Commented Jul 5, 2011 at 1:12
  • What about if you set the textContent property ? – alex Commented Jul 5, 2011 at 1:12
  • 2 Well a new line in HTML is created using the <br /> element, not a "normal" line break. – Felix Kling Commented Jul 5, 2011 at 1:15
Add a ment  | 

3 Answers 3

Reset to default 3

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

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

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

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

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?

http://api.jquery./text/

发布评论

评论列表(0)

  1. 暂无评论