如何将一个Javascript文件链接到另一个Javascript文件

时间:2020-03-17 06:45:03

标签: javascript html function import include

同一文件夹中有两个文件。 我试图在app1中调用名为app2的greet函数。

app1.html

<script>
  function greet() {
    alert('hello from App1')
  }
  // greet() // commented out code
</script>

app2.html

<script type="text/javascript" src="./app1.html"></script>
<script>
  function app2() {
    alert('app2')
  }
  app2()
  greet() // this line of code is not working
</script>

2 个答案:

答案 0 :(得分:0)

我建议使用单独的外部js文件,而不是嵌入的<script>标签,但这也许可以帮忙

How to include js file in another js file?

答案 1 :(得分:0)

如果要在另一个js文件中调用该文件,则必须在调用文件中引用该文件。

例如。

请参阅head部分中的文件。

  <head>     
    <script src="File2.js" type="text/javascript"></script> 
    <script src="File1.js" type="text/javascript"></script> 
  </head>

您可以将body标记如下:

<body>
  <script type="text/javascript">
   Method2(); // Where you want to call method from another JS.
  </script>
 </body>

然后,使用第一个文件

File1.js

function Method1(number) {
  alert("Method1");
}

File2.js

function Method2() {
 Method1("Method1 is called in Method2");
 }