JavaScript字符串中的脚本标记 [英] Script tag in JavaScript string
问题描述
我遇到一个问题,即在JavaScript中的带引号的字符串中有一个结束脚本标记,并且它正在查杀脚本。我认为这不是预期的行为。这方面的一个例子可以在这里看到: http://jsbin.com/oqepe/edit
I am encountering an issue where having a ending script tag inside a quoted string in JavaScript, and it is killing the script. I assume this is not expected behaviour. An example of this can be seen here: http://jsbin.com/oqepe/edit
我感兴趣的测试用例浏览器:Mozilla / 5.0(X11; U; Linux i686; en-US; rv:1.9.1.4)Gecko / 20091028 Ubuntu / 9.10(karmic) Firefox / 3.5.4。
My test case browser for the interested: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.4) Gecko/20091028 Ubuntu/9.10 (karmic) Firefox/3.5.4.
推荐答案
会发生什么?
浏览器HTML解析器将在字符串中看到< / script>
,它会将其解释为脚本元素的结尾。
The browser HTML parser will see the </script>
within the string and it will interpret it as the end of the script element.
请查看此示例的语法颜色:
Look at the syntax coloring of this example:
<script>
var test = 'foo... </script> bar.....';
</script>
请注意, bar 这个词被视为文本内容之外的脚本元素...
Note that the word bar is being treated as text content outside of the script element...
一种常用的技术是使用连接运算符:
A commonly used technique is to use the concatenation operator:
var test = '...... </scr'+'ipt>......';
这篇关于JavaScript字符串中的脚本标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!