我一直在尝试使用javascript的一些技巧,但遇到了一个荒谬的问题:我不能<script>
在javascript字符串中用作子字符串!这是一个例子:
<html>
<head>
<script>
alert("<script></script>");
</script>
</head>
</html>
它应该打印出来<script></script>
,但是我得到了:
");
以HTML格式打印在页面上。
问题:如何在Javascript中使用<script>
后跟</script>
子字符串的方式,为什么这样做呢?
这是JSFiddle。
使您不寒而栗的是</script>
。HTML解析器无法识别Javascript字符串或嵌套<script>
标记,因此会将其解释为initial的结束标记<script>
。也就是说,文档的这一部分被解析为:
<script> (open tag)
alert("<script> (text node - contents of the script)
</script> (close tag)
"); (text node - plain text)
第二个</script>
被忽略,因为没有其他<script>
标签可以关闭。
要解决此问题,请分解</script
以使HTML解析器看不到它。例如:
alert("<script><\/script>");
或者:
alert("<script><" + "/script>");
或者只是将代码放入外部Javascript文件中。仅内联脚本会出现此问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句