通过onclick事件删除<head>标记中的特定<script>标记

Avi*_*way 12 javascript

<head>

    <script type="text/javascript">

        function include(filename, status){
            if(status == 'on'){
                var head = document.getElementsByTagName('head')[0];

                script = document.createElement('script');
                script.src = filename;
                script.type = "text/javascript";

                head.appendChild(script);
            } else {
               // The code that wipes the script tag above
            }
        }

    </script>

</head>

<body>
    <input type="button" value="OPEN" onclick="include('script.js', 'on')">
    <input type="button" value="CLOSE" onclick="include('', 'off')">
</body>
Run Code Online (Sandbox Code Playgroud)

我想通过onclick事件删除标记中的特定标记.当我点击"关闭"按钮时,应该在ELSE区域写入什么代码?

Sir*_*rko 16

最简单的方法是以某种方式保持与创建元素的链接.例如,您可以将include函数放入闭包并使用私有变量来保存引用:

var include = (function(){
   // the reference to the script
   var theScript;

   return function (filename, status){
     if(status == 'on'){
       // adding a script tag
       var head = document.getElementsByTagName('head')[0];

       theScript= document.createElement('script');
       theScript.src = filename;
       theScript.type = "text/javascript";

       head.appendChild( theScript )
     }else{
       // removing it again
       theScript.parentNode.removeChild( theScript );
     }
   }
})();
Run Code Online (Sandbox Code Playgroud)

一个重要的注意事项:通过删除<script>标记,您不会从DOM中删除任何对象,函数等.因此<script>,即使您删除了首先启动它的元素,在该标记内开始的任何操作都将占上风!


Mx.*_*Mx. 5

您也可以向ScriptElement添加一个ID

这将为您工作

function include(filename, status){
  if(status == "on"){
     var head = document.getElementsByTagName('head')[0];

     script = document.createElement('script');
     script.src = filename;
     script.type = "text/javascript";
     script.id = "testScriptName";

     head.appendChild(script);
  }else{
    (elem=document.getElementById("testScriptName")).parentNode.removeChild(elem)
  }
}
Run Code Online (Sandbox Code Playgroud)