Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

javascript - 在另一个js文件中调用JavaScript函数(Calling a javascript function in another js file)

I wanted to call a function defined in a first.js file in second.js file.

(我想调用在second.js文件的first.js文件中定义的函数。)

both files are defined in an HTML file like:

(这两个文件都在HTML文件中定义,例如:)

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

(我想打电话给fn1()中定义first.jssecond.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.

(根据我的搜索答案,如果first.js定义了first.js是可能的,但是根据我的测试,我没有找到任何方法。)

Here is my code:

(这是我的代码:)

second.js

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

first.js

function fn1() {
    alert("external fn clicked");
}
  ask by m0j1 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

(在first.js中声明函数fn1 ,然后在第二秒中就可以拥有fn1();)

1.js:

(1.js:)

function fn1 () {
    alert();
}

2.js:

(2.js:)

fn1();

index.html :

(index.html:)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...