如何从页面动态删除脚本

时间:2013-09-15 18:21:41

标签: javascript jquery jquery-mobile

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

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

现在我正在尝试这个 -

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

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

1 个答案:

答案 0 :(得分:1)

你必须给脚本一个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

相关问题