如何从页面动态删除脚本 [英] How to dynamically remove script from a page

查看:97
本文介绍了如何从页面动态删除脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试的是- http://jsfiddle.net/jhrz9/1/

删除当某人单击按钮#goBack按钮时生成的脚本 现在,当用户单击#runMyCode时,我可以创建和附加脚本和样式标签 但是,一旦我使用#goBack按钮返回上一屏幕,该脚本就会停留在屏幕上,现在我要做的就是删除该脚本,并在单击#runMyCode按钮时再次创建另一个脚本

to remove the script generated when someone clicks the button #goBack button Now i am able to create and append script and style tags when the user clicks the #runMyCode But as soon as i go back to the previous screen using #goBack button the script stays on the screen, now what i want to do is to remove that script and create another one again when i click the #runMyCode button

现在我正在尝试-

var newScript = document.createElement('script'); ;
var newTextNode=document.createTextNode($("#jsTextArea").val());
newScript.type = 'text/javascript';
newScript.appendChild(newTextNode);
document.body.appendChild(newScript);
$('#goBack').click(function(){
newTextNode.parentNode.removeChild(newTextNode);
});

但是由于某种原因,它无法正常工作....

But for some reason it is not working....

推荐答案

您必须给脚本一个ID.

you have to give the script an id.

$("#runMyCode").click(function(){
   $("#resultContainer").html($("#htmlTextArea").val());
   var newScript = document.createElement('script');
   newScript.id = "goback_script";
   var newTextNode=document.createTextNode($("#jsTextArea").val());
   newScript.type = 'text/javascript';
   newScript.appendChild(newTextNode);
   document.body.appendChild(newScript);
   var newStyle = document.createElement('style');
   var newTextNode2=document.createTextNode($("#cssTextArea").val());
   newStyle.type = 'text/css';
   newStyle.appendChild(newTextNode2);
   document.body.appendChild(newStyle);
});
$('#goBack').click(function(){
   var script = document.getElementById("goback_script");
   script.parentElement.removeChild(script);
});

jsFiddle

这篇关于如何从页面动态删除脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆