Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

javascript - Remove specific <script> tag in <head> tag by onclick event

<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>

I want to remove the specific tag in tag by onclick event. What code should be written in the ELSE area, When I click the "CLOSE" botton?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The easiest way, would be to somehow maintain a link to the created element. For example, you could put the include function into a closure and have a private variable, to hold the reference:

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 );
     }
   }
})();

One important note: By removing the <script> tag, you do not remove any of its objects, functions etc. from the DOM. So any action started within that <script> tag will prevail, even if you delete the element, that started it in the first place!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...