如何放置"< / script>"在一个JavaScript字符串? [英] How to put "</script>" in a javascript string?
问题描述
我一直在尝试javascript中的一些技巧,并且出现了一个荒谬的问题:我无法使用< script>
作为javascript中的子字符串字符串!下面是一个例子:
< html>
< head>
< script>
alert(< script>< / script>);
< / script>
< / head>
< / html>
它应该打印出 < script>< /
); $ b脚本>
$ b
在页面上打印出来,就像HTML。
问题: 如何使用< script>
,然后是< / script> ;
子字符串,在一个字符串中,在Javascript中,任何为什么这样做?
这是 JSFiddle ): 你最多的是< / script>
.HTML解析器无法识别Javascript字符串或嵌套< script>
标签,所以它将解释为最初的< script>
的结束标签。也就是说,这部分文档被解析为:
< script>(打开标签)
alert(< s cript>(文本节点 - 脚本的内容)
< / script> (关闭标签)
);(文本节点 - 纯文本)
第二个< / script>
被忽略,因为没有其他< script>
标签关闭。
要解决这个问题,请分解< / script
,以便HTML解析器不会看到它。
alert(< script>< \ / script>);
或:
alert(< ; script><+/ script>);
外部Javascript文件,这个问题只出现在内联脚本中。
I've been trying some tricks in javascript and came to a ridiculous problem: I can't use <script>
as a substring in a javascript string! Here is an example:
<html>
<head>
<script>
alert("<script></script>");
</script>
</head>
</html>
It supposed to print out <script></script>
, but instead, I get this:
");
Printed out on the page, as HTML.
Question: How can I use <script>
followed by </script>
substrings, in a String, in Javascript, any why is it acting that way?
Here is JSFiddle of it :)
What's tripping you up is the </script>
. The HTML parser doesn't recognize Javascript strings or nested <script>
tags, so it's interpreting that as the closing tag for the initial <script>
. That is, this part of the document is parsed as:
<script> (open tag)
alert("<script> (text node - contents of the script)
</script> (close tag)
"); (text node - plain text)
The second </script>
is ignored, as there's no other <script>
tag for it to close.
To work around this, break up </script
so that the HTML parser doesn't see it. For instance:
alert("<script><\/script>");
or:
alert("<script><" + "/script>");
or just put the code in an external Javascript file. This issue only arises for inline scripts.
这篇关于如何放置"< / script>"在一个JavaScript字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!