Javascript动态地将字符串附加到脚本元素

时间:2017-02-02 14:16:21

标签: javascript jquery

如何在html中附加以下变量(作为脚本标记的一部分)。

invokedynamic

我使用以下代码收到无效的令牌错误;

var x = '-----BEGIN CERT\nMIIDvTCCAqWgAsdfsdfTAktS\nMR4wHAYDVQQKExVTb2Z0Zm9ydW0gQ29yc45656b24xHjAcBgNVBAsTFVNlY3Vy\naXR5IFJORCBEaXZpc2lvbQQKDAhq\ncG1vcmdhbjER\n-----END CERT-----\n;';

3 个答案:

答案 0 :(得分:1)

你需要逃避回车。同样,@ maxzoom建议,你可能想使用innerText而不是innerHTML。

$('.site-overlay-toggle .btn').on("click", function(){

    if ( $(".page-title").is(':visible') ) {
       $( ".page-title" ).hide();
    } else {
       $( ".page-title" ).show();   
    }

});
var script = document.createElement('script');
  script.type = 'text/javascript';
  script.innerHTML = "var x = '-----BEGIN CERT\\nMIIDvTCCAqWgAsdfsdfTAktS\\nMR4wHAYDVQQKExVTb2Z0Zm9ydW0gQ29yc45656b24xHjAcBgNVBAsTFVNlY3Vy\\naXR5IFJORCBEaXZpc2lvbjEcMBoGA1UEAxMTU29mdGZvcnVtIFB1YmxpYyBDQTE\\nODQzMzhaFw0yMj45645gNVBAYTAktSMREwDwYDVQQKDAhq\\ncG1vcmdhbjER\\n-----END CERT-----\\n;'; console.log(x);";
  $("body").append(script);

检查员在这里开始行动......

enter image description here

答案 1 :(得分:1)

要在字符串中处理嵌入式表达式(如换行符\n),可以使用Template literals表示法,如下所示:

var script = document.createElement('script');
script.type = 'text/javascript';
var content = "var x = `-----BEGIN CERT\nMIIDvTCCAqWgAsdfsdfTAktS\nMR4wHAYDVQQKExVTb2Z0Zm9ydW0gQ29yc45656b24xHjAcBgNVBAsTFVNlY3Vy\naXR5IFJORCBEaXZpc2lvbjEcMBoGA1UEAxMTU29mdGZvcnVtIFB1YmxpYyBDQTE\nODQzMzhaFw0yMj45645gNVBAYTAktSMREwDwYDVQQKDAhq\ncG1vcmdhbjER\n-----END CERT-----\n`;";
content += "console.log(x);";
script.innerHTML = content;
$("body").append(script);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

在浏览器中查看生成的源时,脚本存在于 body 元素中:

enter image description here

答案 2 :(得分:0)

你应该这样试试:

var x = '-----BEGIN CERT\nMIIDvTCCAqWgAsdfsdfTAktS\nMR4wHAYDVQQKExVTb2Z0Zm9ydW0gQ29yc45656b24xHjAcBgNVBAsTFVNlY3Vy\naXR5IFJORCBEaXZpc2lvbjEcMBoGA1UEAxMTU29mdGZvcnVtIFB1YmxpYyBDQTE\nODQzMzhaFw0yMj45645gNVBAYTAktSMREwDwYDVQQKDAhq\ncG1vcmdhbjER\n-----END CERT-----\n;'

var script = `<script type="text/javascript">${x}</script>`

$("body").append(script);