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

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

问题描述

我的HTML中有2个div.

I have 2 divs in my HTML.

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

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

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

我尝试在onclick事件中包含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);

这包括head部分中的script标记,但未加载,因为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?

预先感谢.

推荐答案

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

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

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

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.

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

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