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


当前回答

是的,你可以。你需要将这两个JS文件引用到.aspx页面

<script language="javascript" type="text/javascript" src="JScript1.js">
 </script>

    <script language="javascript" type="text/javascript" src="JScript2.js">
    </script>

JScript1.js

function ani1() {
    alert("1");
    ani2();
}

JScript2.js

function ani2() {
    alert("2");
}

其他回答

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

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

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

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";
}

这里是工作示例。

对于那些想在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。