我们可以在另一个 JS 文件中调用用一个 JavaScript 编写的函数吗?

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

本文介绍了我们可以在另一个 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.

文件1.js

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

文件2.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 编写的函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:我们可以在另一个 JS 文件中调用用一个 JavaScript 编写的函数吗?

基础教程推荐