\n is not creating a new line between text in javascript

前端 未结 4 1650
迷失自我
迷失自我 2021-01-17 05:41

I have a piece of JavaScript that is supposed to update a in my HTML:

var StringContent = ({
    \"a\": \'Some String a\',
    \"b\": \'Some string b\',
            


        
相关标签:
4条回答
  • 2021-01-17 06:01

    You should replace \n by <br> since innerHTML takes an HTML string (in HTML, \n merges with adjacent spaces but does not produce a carriage return except for elements with the style white-space:pre-wrap as noted by MaxArt) :

    document.getElementById("overlaycontent").innerHTML = (
        StringContent.a + '<br>' +
        StringContent.b + '<br>' +
        StringContent.c,
    )
    
    0 讨论(0)
  • 2021-01-17 06:14

    CSS! white-space! pre-wrap! Learn about it!

    <div style="white-space: pre-wrap">
    
    
    
    
                           SPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACE!
    
    Newlines totally work now!
    </div>
    
    0 讨论(0)
  • 2021-01-17 06:15

    \n (or sometimes \r\n) will work when outputting to a text element such as <textarea> or to a .txt document, but <br> is required for HTML.

    0 讨论(0)
  • 2021-01-17 06:19

    for innerHTML you need '<br />'

    document.getElementById("overlaycontent").innerHTML = (
        StringContent.a + '<br />' +
        StringContent.b + '<br />' +
        StringContent.c
        )
    

    but for an alert you can use : String.fromCharCode(10) instead of '\n'

    alert(
        StringContent.a + String.fromCharCode(10) +
        StringContent.b + String.fromCharCode(10) +
        StringContent.c
        )
    
    0 讨论(0)
提交回复
热议问题