如何在“点击"期间加载外部 Javascript 文件事件? [英] How to load an external Javascript file during an "onclick" event?

查看:39
本文介绍了如何在“点击"期间加载外部 Javascript 文件事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 HTML 中有 2 个 div.

<div id="div2"></div>

点击div2"我想加载一个外部 javascript 文件,例如https://abcapis.com/sample.js".

我尝试在 onclick 事件中包含 JS 文件,如下所示,

var script = document.createElement(script");script.type = "text/javascript";script.src = "https://abcapis.com/sample.js";document.getElementsByTagName("head")[0].appendChild(script);

这包括 head 部分中的 script 标签,但没有加载,因为 script 标签只会在页面加载时加载(如果我错了,请在此处纠正我).

还有其他方法可以继续吗?

提前致谢.

解决方案

使用 jQuery 的 $.getScript() 函数应该为您完成这项工作.

这是一段示例代码:

$(button").click(function(){$.getScript(demo_ajax_script.js");});

如果您不使用 jQuery,您将不得不学习如何使用 AJAX 将新脚本动态加载到您的页面中.

I have 2 divs in my HTML.

<div id="div1"></div>
<div id="div2"></div>

On clicking the "div2" I want to load an external javascript file say for example "https://abcapis.com/sample.js".

I tried including the JS file on onclick event like below,

var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://abcapis.com/sample.js"; 
document.getElementsByTagName("head")[0].appendChild(script);

This included the script tag in the head section but did not load since the script tag will be loaded on page load only (correct me here if I'm wrong).

Is there any other way that I could proceed?

Thanks in Advance.

解决方案

Using jQuery's $.getScript() function should do the job for you.

Here is a slice of sample code:

$("button").click(function(){
  $.getScript("demo_ajax_script.js");
}); 

If you are not using jQuery, you're going to have to learn how to use AJAX to dynamically load new script into your page.

这篇关于如何在“点击"期间加载外部 Javascript 文件事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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