简体   繁体   English

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

[英]How do I link a Javascript file into another Javascript file

There are two files here in the same folder.这里有两个文件在同一个文件夹中。 I am trying to invoke a function named greet of app1 in app2 .我正在尝试在app2调用一个名为greet of app1的函数。

app1.html应用程序1.html

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

app2.html 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>

I would recomend have separate external js files instead of an embedded <script> tag, but maybe this can help我建议使用单独的外部 js 文件而不是嵌入的<script>标签,但这也许会有所帮助

How to include js file in another js file? 如何在另一个js文件中包含js文件?

If you want to call the file in an another js file then you have to refer that file in the calling file.如果要在另一个js文件中调用该文件,则必须在调用文件中引用该文件。

Ex.前任。

Refer the files in the head section.请参阅head部分中的文件。

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

you can have your body tag something like this:你可以让你的body标签是这样的:

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

then, using first file然后,使用第一个文件

File1.js文件1.js

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

File2.js文件2.js

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM