JavaScript 需要发送 Esc 字符 \n 或文本 Return <p> 到 HTML/Browser

JavaScript Needs to Send Esc Character \n or Text Return <p> to HTML/Browser

1) 在解释器中执行 JavaScript 时 - 我可以使用 esc 序列将一些文本放在第二行 注意:此屏幕截图中 myHeading.textContent 的值与后续两个

中的不同
   > myHeading.textContent + " \n How are things?"
   < "Joshua Tree is swell, Laurel Ruth Shimer 
   How are things?" = 

2) 但是,当我通过从浏览器 (Safari) 调用 html 来使用相同的想法进行测试时,我认为 '\n' 只是被视为 尽管我是在 html 内完成的 - HTML 当我在下一行放一些东西时并没有做任何特别的事情。这当然有道理。

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

3) 如果我尝试添加一个 html 标签,

,该标签只是作为文本的一部分包含在内。 html 引擎(我不知道该怎么称呼它)不会将其读取为实际字符

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

...

我有一个(也许两个?)关于将 html 放入数组的 Whosebug 响应,但我认为这不是一回事。

虽然您的 shell 确实 理解 \n 代表什么,但现代浏览器不理解。改为表示 newline on a web page, you should use the <br> 元素。

现在,正如您已经体验过的那样,您无法使用 textContent 属性 插入 HTML 元素。这是因为textContent属性代表的是text一个元素,不是html -- 您设置的任何字符串都将被视为 text.

要设置元素的内部 html,请使用 innerHTML属性。

像这样的东西应该可以满足您的需求:

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