在脚本标记下编写内容

Writing Content Under Script Tags

本文关键字:脚本      更新时间:2023-09-26

我正在尝试使用javascript在页面下动态创建脚本标记。到目前为止,我已经能够创建它,能够设置它的类型和src。现在我的问题是,有没有办法将src定义为不同的页面,而不是在同一页面上分配其内容?让我写我的代码,使它更有意义:

var script = document.createElement("script");
script.type = "text/javascript";
script.src = 'custom.js';

现在有没有什么方法可以通过这样做来分配内容:

script.content = 'document.write("stackoverflow")';
script.html = 'document.write("stackoverflow")';

我不确定它们是否存在,只是猜测我是否能做这样的事情。

你可以做:

var script_tag = document.createElement('script');
script_tag.type = 'text/javascript';
script_tag.text = 'alert("hello world")';
document.body.appendChild(script_tag);

在实践中,是否设置类型属性可能无关紧要,但它会给人一种温暖的内在感觉。

可以使用"Scripts.text"读取或写入脚本。它是脚本数据对象模型(DOM)的一部分。由于某种原因,它与其他HTML标记不同。示例:"myScript.innerHTML"通常不起作用,但"scripts.namedItem("myScript").text"起作用。

<p>Change scripts.text <a href="https://www.w3schools.com/jsref/prop_script_text.asp">https://www.w3schools.com/jsref/prop_script_text.asp</a>
</p>
<p>Script Object <a href="https://www.w3schools.com/jsref/dom_obj_script.asp">https://www.w3schools.com/jsref/dom_obj_script.asp</a>
</p>
<canvas id="Canvas1" style="border: 5px solid cyan"></canvas>
<p id="Para1">...</p>
<button onclick="ChangeScript()">Change Script</button>
<button onclick="DrawIt()">Drawit</button>
<button onclick="para1.innerHTML=script1.text;">Show Script</button>
<script id="Script1"></script>
<script>
  function ChangeScript() {
    script1.text = "function DrawIt(){canvas1.fillRect(1,2,30,40)}"
  }
  //Note: changing the script text more than once may not work.
  canvas1 = document.getElementById("Canvas1").getContext("2d");
  script1 = document.scripts.namedItem("Script1");
  para1 = document.getElementById("Para1")
</script>
<a href="http://www.w3schools.com/code/tryit.asp?filename=FCR1ZI3MBN77">Try it Yourself, Change scripts.text</a>