簡體   English   中英

我可以寫一個<script> tag inside a <script> tag

[英]Can I write a <script> tag inside a <script> tag

這是我的代碼。 當屏幕寬度小於 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>
<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>

您可以使用{{html "</sc"+"ript>"}}代替</script>

說明【更新】:

當您在帶引號的(文字)字符串中使用</script> HTML 標記時,該標記被視為結束標記而不是字符串的一部分。 所以你不能直接在腳本部分中使用</script>標簽。

一種解決方法是轉義</script>標簽和/或拆分<script>標簽:

var scriptEnd = "</scr" + "ipt>";
document.write(scriptEnd);

為什么要使用嵌套腳本來修改對象屬性?

由於您已經“在腳本中”,因此可以以更簡單的方式解決它:

<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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM