JavaScript需要发送Esc字符\ n或文本返回<p>到HTML /浏览器

时间:2016-05-13 15:28:12

标签: javascript html html5 safari client-server

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

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

2)但是当我通过从浏览器(Safari)调用html来使用相同的想法进行测试时,我想,'\ n'就是   虽然我在html中完成了这个 - 当我在下一行放置东西时,HTML没有做任何特别的事情。当然,这是有道理的。

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

enter image description here  3)如果我尝试添加一个html标签,

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

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

enter image description here   ...

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

1 个答案:

答案 0 :(得分:2)

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