我们可以在另一个JS文件中调用写在一个JS文件中的函数吗?有人能帮助我如何从另一个JS文件调用函数吗?


当前回答

ES6:使用<script>在.html中包含许多js文件,你可以只包括一个主文件,例如script.js使用属性type="module"(支持),在script.js中你可以包括其他文件:

<script type="module" src="script.js"></script>

在script.js文件中包含另一个这样的文件:

import { hello } from './module.js';
...
// alert(hello());

在'module.js'中,你必须导出将要导入的函数/类

export function hello() {
    return "Hello World";
}

这里是工作示例。

其他回答

您可以从正在工作的文件中调用在另一个js文件中创建的函数。因此,首先你需要将外部js文件作为-添加到html文档中

<html>
<head>
    <script type="text/javascript" src='path/to/external/js'></script>
</head>
<body>
........

在外部javascript文件中定义的函数

$.fn.yourFunctionName = function(){
    alert('function called succesfully for - ' + $(this).html() );
}

要在当前文件中调用此函数,只需将该函数称为-

......
<script type="text/javascript">
    $(function(){
        $('#element').yourFunctionName();
    });
</script>

如果要将参数传递给函数,则将函数定义为-

$.fn.functionWithParameters = function(parameter1, parameter2){
        alert('Parameters passed are - ' + parameter1 + ' , ' + parameter2);
}

并在当前文件中调用此函数为-

$('#element').functionWithParameters('some parameter', 'another parameter');

ES6:使用<script>在.html中包含许多js文件,你可以只包括一个主文件,例如script.js使用属性type="module"(支持),在script.js中你可以包括其他文件:

<script type="module" src="script.js"></script>

在script.js文件中包含另一个这样的文件:

import { hello } from './module.js';
...
// alert(hello());

在'module.js'中,你必须导出将要导入的函数/类

export function hello() {
    return "Hello World";
}

这里是工作示例。

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

I.e.

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所正确指出的。另一种方法也可以。

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)。

对于那些想在Node.js(在服务器端运行脚本)中执行此操作的人来说,另一种选择是使用require和module.exports。下面是一个关于如何创建一个模块并将其导出以供在其他地方使用的简短示例:

file1.js

const print = (string) => {
    console.log(string);
};

exports.print = print;

file2.js

const file1 = require('./file1');

function printOne() {
    file1.print("one");
};

只要两者都被网页引用,是的。

你只需调用这些函数,就好像它们在同一个JS文件中一样。