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

时间:2013-02-05 13:01:50

标签: 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>

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

3 个答案:

答案 0 :(得分:15)

最简单的方法是以某种方式维护指向已创建元素的链接。例如,您可以将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 );
     }
   }
})();

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

答案 1 :(得分: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)
  }
}

答案 2 :(得分:1)

尝试使用:

function include(filename, status){
  var head = document.getElementsByTagName('head')[0];
  if(status == on){
     script = document.createElement('script');
     script.src = filename;
     script.type = text/javascript;
     head.appendChild(script)
  }
  else if(status == 'off'){
     var scripts = head.getElementsByTagName('script');
     if(scripts.length > 0){
        head.removeChild(scripts[0]);
     }
  }
}