简体   繁体   English

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

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

I need to add in some javascript code onto my page after an onclick. 在点击之后,我需要在页面上添加一些JavaScript代码。 I have the following code but nothing happens on the button click and the page just outputs: 我有以下代码,但单击按钮并没有任何反应,页面仅输出:

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

Here is my code: 这是我的代码:

<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>

I got it to work by escaping the forward slash in </script>. 我通过在</ script>中转义正斜杠来使其工作。 The closing script tag is not allowed in inline Javascript, as it messes with the way the code is parsed: 内联Javascript中不允许使用结束脚本标记,因为它会干扰代码的解析方式:

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

This is actually a surprisingly simple task and doesnt require Jquery -- although you can execute the function with or without Jquery, however you like. 这实际上是一个非常简单的任务,并且不需要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);
}

You can also add in an onload event if you want: 您还可以根据需要添加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