javascript 我可以在 <script> 标签内写一个 <script> 标签吗
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33969544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I write a <script> tag inside a <script> tag
提问by Amar Ilindra
This is my code. I'm trying to stop running an external js file when screen width is less than 1025.
这是我的代码。当屏幕宽度小于 1025 时,我试图停止运行外部 js 文件。
<script type="text/javascript">
var gdsize = 1025;
if(window.innerWidth>=gdsize) {
<script>
window.cookieconsent_options = {"message":"\"Geek Dashboard uses cookies to make sure you get the best experience on our website.\" -","dismiss":"It's OK","learnMore":"More Details Here","link":"http://www.geekdashboard.com/cookies/","theme":"dark-bottom"};
}
</script>
</script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/cookieconsent2/1.0.9/cookieconsent.min.js"></script>
回答by Vikrant
<script type="text/x-jQuery-tmpl">
var gdsize = 1025;
if(window.innerWidth>=gdsize) {
<script type="text/javascript">
<!-- Some javascript here -->
window.cookieconsent_options = {"message":"\"Geek Dashboard uses cookies to make sure you get the best experience on our website.\" -","dismiss":"It's OK","learnMore":"More Details Here","link":"http://www.geekdashboard.com/cookies/","theme":"dark-bottom"};
}
{{html "</sc"+"ript>"}}
</script>
You can use {{html "</sc"+"ript>"}}
in place of </script>
您可以使用{{html "</sc"+"ript>"}}
代替</script>
Explanation [update]:
说明【更新】:
When you use a </script>
HTML tag inside a quoted (literal) string, the tag is treated as a closing tag rather than as a portion of the string. So you cannot directly use the </script>
tag inside a script section.
当您</script>
在带引号的(文字)字符串中使用HTML 标记时,该标记将被视为结束标记而不是字符串的一部分。所以你不能直接</script>
在脚本部分中使用标签。
One work-around is to escape the </script>
tags and/or split up the <script>
tags:
一种解决方法是转义</script>
标签和/或拆分<script>
标签:
var scriptEnd = "<\scr" + "ipt>";
document.write(scriptEnd);
回答by Shomz
Why would you use a nested script to modify an object property?
为什么要使用嵌套脚本来修改对象属性?
It can be solved in a much simpler way since you're already "in the script":
由于您已经“在脚本中”,因此可以以更简单的方式解决它:
<script type="text/javascript">
var gdsize = 1025;
if(window.innerWidth>=gdsize) {
window.cookieconsent_options = {"message":"\"Geek Dashboard uses cookies to make sure you get the best experience on our website.\" -","dismiss":"It's OK","learnMore":"More Details Here","link":"http://www.geekdashboard.com/cookies/","theme":"dark-bottom"};
}
</script>