JavaScript 中的转义序列似乎不起作用?我正在用 HTML 5 编写,并且是一个相当新手。单引号、双引号和反斜杠确实有效。但换行符\n、退格键\b、回车符\r 和制表符\t 不起作用。谁能告诉我为什么不呢?或者解决方法?
<script type="text/javascript">
document.write("Hey bob!, \'You is da bomb!");
</script>
谢谢。
最佳答案
But newline \n, backspace \b, carriage return \r, and tab \t don't work.
这些字符在 HTML 中没有以任何特殊方式处理,它们只是空格。如果要在 HTML 中创建换行符,则必须使用 <br />
标签。
来自specification (强调我的):
This specification does not indicate the behavior, rendering or otherwise, of space characters other than those explicitly identified here as white space characters. For this reason, authors should use appropriate elements and styles to achieve visual formatting effects that involve white space, rather than space characters.
需要明确的是:这与 JavaScript 没有任何关系,只与 HTML 的工作方式有关。小例子:Fiddle 。我的源代码中有一个换行符(与使用 document.write('Foo \n bar')
创建的换行符相同),但浏览器不会呈现换行符。
如果您使用alert
或console.log
而不是document.write
您将看到实际生成的字符串,因为该字符串不显示在 HTML 上下文中。
关于javascript - JavaScript 中的转义序列不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21354397/