如何在html中附加以下变量(作为脚本标记的一部分)。
invokedynamic
我使用以下代码收到无效的令牌错误;
var x = '-----BEGIN CERT\nMIIDvTCCAqWgAsdfsdfTAktS\nMR4wHAYDVQQKExVTb2Z0Zm9ydW0gQ29yc45656b24xHjAcBgNVBAsTFVNlY3Vy\naXR5IFJORCBEaXZpc2lvbQQKDAhq\ncG1vcmdhbjER\n-----END CERT-----\n;';
答案 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);
检查员在这里开始行动......
答案 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 元素中:
答案 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);