javascript - how to insert a script tag to div?

后端 未结 4 1517
猫巷女王i
猫巷女王i 2020-12-21 08:34

How to do that:

document.getElementById(\'target\').innertHTML = \"<script> alert(1); <script>\";
4条回答
  •  春和景丽
    2020-12-21 09:28

    You cannot use innerHTML for scripts anymore. It won't work and the console will not show any error. Instead you dynamically add scripts.

    This is for external scripts:

    var newScript = document.createElement("script");
    newScript.src = "http://www.example.com/my-script.js";
    target.appendChild(newScript);
    

    And this is for inline scripts:

    var newScript = document.createElement("script");
    var inlineScript = document.createTextNode("alert('Hello World!');");
    newScript.appendChild(inlineScript); 
    target.appendChild(newScript);
    

    Credit to Daniel Crabtree

提交回复
热议问题