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

2022-01-25 00:00:00 include 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).

相关文章