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


当前回答

我想到了另一个好办法。 窗口(“functioName”)(params);

其他回答

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

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

您可以从正在工作的文件中调用在另一个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');

对于那些想在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");
};

下面是一个更具描述性的例子,附带一个CodePen代码片段:

1.js

function fn1() {
  document.getElementById("result").innerHTML += "fn1 gets called";
}

2.js

function clickedTheButton() {
  fn1();
} 

index . html

<html>
  <head>
  </head>
  <body>
    <button onclick="clickedTheButton()">Click me</button>
    <script type="text/javascript" src="1.js"></script>
    <script type="text/javascript" src="2.js"></script>
  </body>
 </html>

输出

试试这个CodePen代码片段:link。

我想到了另一个好办法。 窗口(“functioName”)(params);