为什么JavaScript换行符不能在HTML内使用? [英] Why doesn’t JavaScript newlines work inside HTML?

查看:64
本文介绍了为什么JavaScript换行符不能在HTML内使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下内容:

<html>
  <body>
    <script type="text/javascript">
      document.write('Hello\nWorld')
    </script>
  </body>
</html>

众所周知, \ n 不起作用,我必须改用< br> .如果我链接到外部 .js 文件,该方法也不起作用.这是我的问题:

As you probably all know, \n doesn’t work and I have to use <br> instead. It won’t work either if I link to an external .js file. Here are my questions:

  1. 为什么 \ n 不起作用?
  2. 为什么< br> 还能工作?
  3. 是否可以使 \ n 以某种方式工作?
  4. 我知道 \ t 也不起作用.还有其他无法在HTML文件中使用的东西吗?
  5. 不相关的问题(我不想为此开一个新问题):我安装了Node.js以便能够从vim中试用JS脚本,但是当我运行此脚本时,出现错误" document 未定义".当我从REPL尝试时,也会发生同样的事情.有什么想法吗?
  1. Why doesn’t \n work?
  2. Why does <br> even work? Shouldn’t everything that’s inside the script tags be strictly JavaScript instead of a dirty mix between HTML and JS?
  3. Is it possible to make \n work somehow?
  4. I know \t doesn’t work either. Any other stuff that won’t work inside HTML files?
  5. Unrelated question (I didn’t want to open a new question just for this): I installed Node.js to be able to try out JS scripts from inside vim but when I run this script I get the error "document is not defined". Same thing happens when I try from the REPL. Any ideas?

在搜索类似问题时,我得到的只是我应该使用< br> 而不是 \ n .

When searching for similar questions, all I got was that I should use <br> instead of \n.

推荐答案

\ n 可行.如果您有各种调试器(或类似的开发人员工具),则可以看到文档源,并且您会看到确实有换行符.问题在于您查看页面的方式:正在阅读其源代码,而是将其作为HTML文档阅读.HTML中的空格折叠为一个空格.因此,当您更改源代码时,它确实的确发生了更改,尽管当解释为HTML文档时,该更改不会显示.

\n works. If you have a debugger of sorts (or similar developer tool), you can see the document source, and you will see that there is indeed a newline character. The problem is the way you are looking at the page: you’re not reading its source, you’re reading it as an HTML document. Whitespace in HTML is collapsed into a single space. So when you change the source, it does indeed change, although when interpreted as an HTML document, that change isn’t shown.

您的Node.js错误很可能是由您在服务器上运行浏览器脚本引起的.IE.引用 document 的脚本旨在在具有DOM等的浏览器中运行.尽管通用节点进程因为不是浏览器而没有这样的全局对象.这样,当您尝试运行引用名为 document 的全局对象的代码时,假设该对象与浏览器中的对象相同,则会抛出错误. document.write 不存在;如果要写入屏幕,请尝试 console.log 或查看其他util函数.

Your Node.js error is most probably caused by the fact that you’re running browser scripts on the server. I.e. scripts that refer to the document are intended to be run in a browser, where there is a DOM etc. Although a generic node process doesn’t have such a global object because it isn’t a browser. As such, when you try and run code that references a global object called document on the assumption that it exists just like in the browser, it will throw an error. document.write doesn’t exist; if you want to write to the screen, try console.log or look into the other util functions.

这篇关于为什么JavaScript换行符不能在HTML内使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆