且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我需要在JavaScript中转义'/'字符?

更新时间:2023-09-29 19:31:04

问题可能是网络浏览器看到< / script> 序列并确定这是脚本块的结束。

The problem may be that the web browser sees the "</script>" sequence and decides that's the end of the script block.

除了像你一样使用转义序列之外的另一种修复问题的方法是将它分成2个字符串连接:

Another way to fix the problem aside from using an escape sequence like you did is to break it apart into 2 strings that are concatenated:

"<" + "/script>" 

您所看到的行为不是浏览器中的错误。

The behavior you're seeing isn't a bug n the part of the browser.

浏览器不会查看脚本块,它们只是将内容传递给脚本引擎。 < / script> 序列是他们知道他们已经到达块的末尾,并且因为浏览器不解释块的内容,它无法知道它是在脚本代码中的文字字符串的上下文中。

Browsers don't "look inside" a script block, they just pass the content to the script engine. The "</script>" sequence is how they know they've come to the end of the block, and since the browser doesn't interpret the contents of the block, it has no way to know that it's in the context of a literal string in the script code.

请记住,浏览器可以支持更多的脚本语言,而不仅仅是Javascript,即使它并不常见。 Internet Explorer支持VBscript(我认为任何脚本语言都可以由Windows脚本主机运行,但我不确定)。当将脚本块的能力放回到浏览器的时候,没有人可以肯定Javascript最终会如此普遍。

Remember that browsers can support more script languages than just Javascript, even if it's not commonly seen. Internet Explorer supports VBscript (and I think any scripting language that can be run by a windows script host, but I'm not sure about that). And when the ability to have script blocks was put into browsers way back when, no one could be sure that Javascript would end up being so universal.