我们可以在另一个JS文件中调用用一个JavaScript编写的函数吗? [英] Can we call the function written in one JavaScript in another JS file?

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

问题描述

我们可以在另一个JS文件中调用一个JS文件中编写的函数吗?任何人都可以帮我如何从另一个JS文件调用该函数?

Can we call the function written in one JS file in another JS file? Can anyone help me how to call the function from another JS file?

推荐答案

只要包含函数定义的文件,就可以调用该函数,就好像它在同一个JS文件中一样在第一次使用该函数之前已经加载。

The function could be called as if it was in the same JS File as long as the file containing the definition of the function has been loaded before the first use of the function.

File1.js

function alertNumber(number) {
    alert(number);
}

File2.js

function alertOne() {
     alertNumber("one");
}

HTML

<head>
....
    <script src="File1.js" type="text/javascript"></script> 
    <script src="File2.js" type="text/javascript"></script> 
....
</head>
<body>
....
    <script type="text/javascript">
       alertOne();
    </script>
....
</body>

另一种方式不起作用。
正确无误由 Stuart Wakefield 指出。另一种方式也可以。

The other way won't work. As correctly pointed out by Stuart Wakefield. The other way will also work.

HTML

<head>
....
    <script src="File2.js" type="text/javascript"></script> 
    <script src="File1.js" type="text/javascript"></script> 
....
</head>
<body>
....
    <script type="text/javascript">
       alertOne();
    </script>
....
</body>

什么是行不通的:

HTML

<head>
....
    <script src="File2.js" type="text/javascript"></script> 
    <script type="text/javascript">
       alertOne();
    </script>
    <script src="File1.js" type="text/javascript"></script> 
....
</head>
<body>
....
</body>

虽然在调用时定义了 alertOne ,在内部它使用一个仍未定义的函数( alertNumber )。

Although alertOne is defined when calling it, internally it uses a function that is still not defined (alertNumber).

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

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