JavaScript Needs to Send Esc Character \\n or Text

2019-09-05 23:33发布

问题:

1) When executing JavaScript in the interpreter - I can use an esc sequence to put some text on a second line NOTE: the value of myHeading.textContent was different in this screen shot than in the succeeding two

   > myHeading.textContent + " \n How are things?"
   < "Joshua Tree is swell, Laurel Ruth Shimer 
   How are things?" = $1

2) But when I use the same idea testing by calling html from a browser (Safari), the '\n' is, I would think, just seen as though I had done this within html - HTML doesn't do anything special when I put something on the next line. This makes sense, of course.

   var myHeading = document.querySelector('h1');
   myHeading.textContent = 'Good to see you again, ' + storedName +  ' \n    
  Write me again soon.' ;

3) If I attempt to add an html tag,

, that tag is just included as part of the text. It's not read by the html engine (I don't know what to call that) as actual characters

   var myHeading = document.querySelector('h1');
   myHeading.textContent = 'Good to see you again, ' + storedName +  ' <p>  
   Write me again soon.' ;

...

I a (maybe two?) Stackoverflow responses about putting html into an array, but I don't think that is the same thing.

回答1:

Whilst your shell does understand what \n represents, modern browsers do not. To represent a newline on a web page, you should use the <br> element instead.

Now, as you've already experienced, you cannot interpolate an HTML element using the textContent property. This is because the textContent property represents the text of an element, not the html -- any string you set will be treated as text.

To set the inner html of an element, use the innerHTML property.

Something like this should work for your needs:

myHeading.innerHTML = 
    'Good to see you again, ' + storedName +  ' <br>  Write me again soon.' ;