繁体   English   中英

将JavaScript代码添加到jquery onclick事件的页面上

[英]Add javascript code to page on jquery onclick event

在点击之后,我需要在页面上添加一些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>

我通过在</ script>中转义正斜杠来使其工作。 内联Javascript中不允许使用结束脚本标记,因为它会干扰代码的解析方式:

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

这实际上是一个非常简单的任务,并且不需要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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM