开发者

Script tag in JavaScript string [duplicate]

This question already has answers here: Why split the <script> tag when writing it with document.write()? (5 answers) Closed 8 years ago.

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

My test case browser for the interested: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.开发者_StackOverflow社区4) Gecko/20091028 Ubuntu/9.10 (karmic) Firefox/3.5.4.


What happens?

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>

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>......';


You need to escape it, else it will be a part of the HTML.

var test = 'what the hell... \<\/script\> \<h1\>why?!?!?!\<\/h1\>';
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜