在另一个js文件中调用一个javascript函数 [英] Calling a javascript function in another js file

查看:70
本文介绍了在另一个js文件中调用一个javascript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 < script type =text / javascriptsrc =first.js >< /脚本> 
< script type =text / javascriptsrc =second.js>< / script>

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



编辑:

下面是示例代码:

second.js < (

pre $ 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:

 < script type =text / javascriptsrc =1.js>< / script> 
< script type =text / javascriptsrc =2.js>< / script>

它可以正常工作:)


I wanted to call a function defined in a first.js file in second.js file. both files are defined in an HTML file like:

<script type="text/javascript" src="first.js"></script>
<script type="text/javascript" src="second.js"></script>

I want to call fn1() defined in first.js in second.js. From my searches answers were if first.js is defined first it is possible but from my tests I haven't found any way to do that. Thanks

Edit:
Here's sample codes:
second.js

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

first.js

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

解决方案

A function cannot be called unless it was defined in the same file or one loaded before the attempt to call it.

A function cannot be called unless it is in the same or greater scope then the one trying to call it.

You declare function fn1 in first.js, and then in second you can just have fn1();

1.js :

function fn1 (){
    alert();
}

2.js :

fn1();

index.html :

<script type="text/javascript" src="1.js"></script>
<script type="text/javascript" src="2.js"></script>

It works fine :)

这篇关于在另一个js文件中调用一个javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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