HTML引用另一个js文件的方法,在另一个js文件中调用一个javascript函数

在另一个js文件中调用一个javascript函数

我想调用second.js文件中的first.js文件中定义的函数。 这两个文件在HTML文件中定义如下:

我想调用second.js中first.js中定义的fn1()。 从我的search答案是,如果first.js首先定义是可能的,但从我的testing,我还没有find任何方式来做到这一点。 谢谢

编辑:

这里是示例代码:

second.js

document.getElementById("btn").onclick = function(){ fn1(); }

first.js

function fn1(){ alert("external fn clicked"); }

一个函数不能被调用,除非它被定义在同一个文件中,或者在尝试调用它之前被加载。

一个函数不能被调用,除非它处于与调用它相同或更大的范围内。

你在first.js中声明函数fn1,然后你可以只有fn1();

1.js:

function fn1 (){ alert(); }

2.js:

fn1();

index.html:

它工作正常:)

你可以在first.js把这个函数变成一个全局variables,看看闭包 ,不要把它放在document.ready

你也可以使用ajax

$.ajax({ url: "url to script", dataType: "script", success: success });

同样你可以使用jQuery getScript

$.getScript( "ajax/test.js" ) .done(function( script, textStatus ) { console.log( textStatus ); }) .fail(function( jqxhr, settings, exception ) { $( "div.log" ).text( "Triggered ajaxError handler." ); });

第一JS:

function fn(){ alert("Hello! Uncle Namaste...Chalo Kaaam ki Baat p Aate h..."); }

第二JS:

$.getscript("url or name of 1st Js File",function(){ fn(); });

希望这有助于…快乐编码。

如果您的服务器允许它提高速度,请使用caching。

var extern =(url)=> { // load extern javascript let scr = $.extend({}, { dataType: 'script', cache: true, url: url }); return $.ajax(scr); } function ext(file, func) { extern(file).done(func); // calls a function from an extern javascript file }

然后像这样使用它:

ext('somefile.js',()=> myFunc(args) );

或者,制作一个原型,让它更加灵活。 所以你不必每次定义文件,如果你调用一个函数,或者你想从多个文件中获取代码。

first.js

function first() { alert("first"); }

Second.js

var imported = document.createElement("script"); imported.src = "other js/first.js"; //saved in "other js" folder document.getElementsByTagName("head")[0].appendChild(imported); function second() { alert("Second");}

的index.html

method in second js method in firstjs ("included" by the first)
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值