2015-02-10 70 views
2

我需要在onclick后将一些javascript代码添加到我的页面上。我有以下的代码,但什么也没有发生在按钮上点击页面只是输出:在jquery onclick事件页面上添加javascript代码

'); }); }); [button] 

这里是我的代码:

<button type="submit" id="btn">button</button> 

<div id="code"></div> 

<script> 
jQuery(document).ready(function() { 
    jQuery('#btn').click(function(){ 
     jQuery('#code').append('<script>alert("WORKING");</script>'); 
    }); 
}); 
</script> 
+0

你的代码似乎在jsbin工作: http://jsbin.com/likubo/1/edit – 2015-02-10 18:18:57

+0

为什么不只是在按钮被点击后使用布尔变量来切换行为? – pennstatephil 2015-02-10 18:19:01

+2

为什么在运行警报时附加一个运行警报的脚本? – j08691 2015-02-10 18:19:16

回答

0

我得到了它在<逃逸斜杠工作/脚本>。截止脚本标签没有在内嵌的JavaScript允许的,因为它与代码解析的方式打乱:

 jQuery('#code').append('<script>alert("WORKING");<\/script>'); 
0

这其实是一个非常简单的任务,需要犯规jQuery的 - 尽管你可以执行的功能或不用Jquery,但是你喜欢。

function AddNewExternalScriptToThisPage(ExternalScriptURLPath) { 
    var headID = document.getElementsByTagName("head")[0]; 
    var newScript = document.createElement('script'); 
    newScript.type = 'text/javascript'; 
    newScript.src = ExternalScriptURLPath; 
    headID.appendChild(newScript); 
} 

如果你愿意,还可以添加在onload事件:

function AddNewExternalScriptToThisPage(ExternalScriptURLPath) { 
    var headID = document.getElementsByTagName("head")[0]; 
    var newScript = document.createElement('script'); 
    newScript.type = 'text/javascript'; 
    newScript.src = ExternalScriptURLPath; 
    newScript.onload=scriptHasLoadedContinue; 
    headID.appendChild(newScript); 
} 
相关问题