简体   繁体   English

为什么逃避/在javascript'<\\ / script>'?

[英]why escaping / in javascript '<\/script>'?

I have seen everyone doing it tho i dont' get why. 我看到每个人都这样做,我不知道为什么。

document.write('<script src="src"><\/script>');

I mean using the single ' you shouldn't need to esacape chars? 我的意思是使用单曲'你不应该需要esacape chars?

</script> always ends a script block - no matter what (eg HTML comments or CDATA) you do. </script>总是结束一个脚本块 - 无论你做什么(例如HTML注释或CDATA)。 So it must never occur in a script block unless you actually want to end the block and the easiest way to do so is escaping forward slashes (the escaping doesn't do anything; in JavaScript unknown escape sequences just "lose" their backslash). 所以它必须永远不会出现在脚本块中,除非你真的想要结束块,最简单的方法是转义正斜杠(转义不会做任何事情;在JavaScript中未知的转义序列只是“丢失”它们的反斜杠)。

  1. Single and double quoted strings have the same escaping rules. 单引号和双引号字符串具有相同的转义规则。
  2. It prevents </script> from being parsed as an closing tag. 它可以防止</script>被解析为结束标记。

" </script> and " <\\/script> " are the same to JavaScript , but only the first one is interpreted by the HTML parser to contain a HTML closing tag. </script>和” <\\/script> “与JavaScript相同,但只有第一个由HTML解析器解释为包含HTML结束标记。

The HTML-parser will see the </script> in your string as a closing tag and close your initial <script> . HTML解析器将字符串中的</script>视为结束标记并关闭您的初始<script> It does not have the concept of strings. 它没有字符串的概念。

So your piece of JavaScript will only be seen as document.write('<script src="src"> if you dont escape it and the rest, '); 所以你的JavaScript只会被视为document.write('<script src="src">如果你不逃避它,其余的, '); will be seen as a HTML text-node. 将被视为HTML文本节点。

Also, note that you don't have to "escape" the </script> in a particular way. 另请注意,您不必以特定方式“转义” </script> As long as you don't write it exactly like </script> , anything is ok. 只要你不像</script>那样写它,一切都没问题。 Some examples that all work: 一些例子都有效:

document.write('<script src="src"><\/script>');
document.write('<script src="src"></scr' + 'ipt>');
document.write('<script src="src"></' + 'script>');

It's for an XHTML validity. 它适用于XHTML有效性。 You can use a validator for see that : http://validator.w3.org/ . 您可以使用验证器查看: http//validator.w3.org/ You can use a also use CDATA tag. 您也可以使用CDATA标签。 See this similar question for more details : Escaping HTML in jQuery so it's valid 有关更多详细信息,请参阅此类似问题: 在jQuery中转义HTML以使其有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM