问题描述
<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区域写入什么代码?
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?
推荐答案
最简单方式,将以某种方式维护到创建的元素的链接。例如,您可以将include函数放入闭包并使用私有变量来保存引用:
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 );
}
}
})();
一个重要说明:删除< script>
标签,您不会从DOM中删除任何对象,函数等。因此,即使您删除了首先启动它的元素,在< script>
标记内开始的任何操作都将占上风!
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!
这篇关于删除特定的< script>标签在< head>标记为onclick事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!