为什么我需要在JavaScript中转义'/'字符? [英] Why do I need to escape the '/' character in JavaScript?

查看:132
本文介绍了为什么我需要在JavaScript中转义'/'字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

究竟需要在javascript字符串中进行转义。或者,更具体地说,为什么

What exactly needs to be escaped in javascript strings. Or, more specifically, why does

var snaphtml = '<script src="http://seadragon.com/embed/lxe.js?width=auto&height=400px"></script>';

给出语法错误?转义最后的< \ / script> 似乎修复了语法错误,但这对我来说对javascript初学者没有意义。

give a syntax error? Escaping the final <\/script> seems to fix the syntax error, but this doesn't make sense to me as a javascript beginner.

推荐答案

问题可能是网络浏览器看到< / 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.

这篇关于为什么我需要在JavaScript中转义'/'字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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