简体   繁体   English

Javascript动态插入脚本元素

[英]Javascript Dynamically insert script element

I want to insert the following 我想插入以下内容

<script language="javascript">
var x = '-----BEGIN SOME-----\n
-----END SOME-----\n;';
</script>

I know how to do when using a "src" attribute. 我知道使用“ src”属性时的操作。 But in my case, I want to append some variable x in the script. 但就我而言,我想在脚本中附加一些变量x。

var s = document.createElement("script");
s.type = "text/javascript";
s.src = "http://xyz";
$("head").append(s);
   var script = document.createElement( 'script' );
   script.type = 'text/javascript';
   script.innerHTML = 'alert("Hey there... you just appended this script to the body");';
   $("body").append( script );

use innerHTML to dynamically add scripts to your element. 使用innerHTML将脚本动态添加到您的元素。

If I understand correctly what you mean is that you want to generate a <script> tag with variables inside. 如果我正确理解的意思是您想生成一个内部包含变量的<script>标记。 To do this you can use jQuery: 为此,您可以使用jQuery:

$('html').append('<script>console.log("hello world");</script>')

This will display hello world in the console. 这将在控制台中显示hello world Of course you can switch the JavaScript code to whatever you would like. 当然,您可以将JavaScript代码切换为所需的任何代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM