javascript - JavaScript 中的转义序列不起作用?

标签 javascript

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') 创建的换行符相同),但浏览器不会呈现换行符。

如果您使用alertconsole.log而不是document.write您将看到实际生成的字符串,因为该字符串不显示在 HTML 上下文中。

关于javascript - JavaScript 中的转义序列不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21354397/

相关文章:

javascript - URL 链接在 Angularjs 中无法正确重定向

javascript - 如何在javascript中移动数组内的值

javascript - 为什么 Angular 有 isDefined 和 isUndefined 函数?

javascript - 随机重新定位 jQuery UI 对话框(复活节彩蛋)

javascript - Node JS block 文件作为一个文件读取而不中断?

javascript - 如何根据对象中的id添加键和值

javascript - {{x.日期 |日期 :'hh:mm' }} 不起作用

javascript - 执行 javascript 函数的右括号

javascript - React 在 componentDidMount() 的函数内设置状态,传递要更新的参数

javascript - 那么函数没有定义