【问题标题】:How do I link a Javascript file into another Javascript file如何将 Javascript 文件链接到另一个 Javascript 文件
【发布时间】:2020-06-28 05:45:58
【问题描述】:

这里有两个文件在同一个文件夹中。 我正在尝试在app2 中调用app1 的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>

【问题讨论】:

  • 将脚本导出为 JS 文件并在两个页面上导入
  • 您不能将 HTML 用作 JS 文件的 src。您需要只包含 function greet() { alert('hello from App1') } 的 app1.js
  • 谢谢大家的帮助!
  • 还有一个问题。您知道 HTML 代码中的脚本(行执行)是如何工作的吗?所以我需要 app3.html 中的 app1 和 app2 文件,并且如果我在 app3.js 中调用该方法(两个文件中的方法名称相同)。因此,只有写入最低的文件中的方法才会被调用。例如:- 只有 app1 的问候语。 js 将被称为因为它写得最低。
  • @YashJaiswal 同样的事情也一样,你只需要在第三个文件(app3.html)中添加2个文件的引用并调用你想要触发的任何方法。 .

标签: javascript html function import include


【解决方案1】:

我建议使用单独的外部 js 文件而不是嵌入的 &lt;script&gt; 标记,但也许这会有所帮助

How to include js file in another js file?

【讨论】:

  • 虽然理论上这可以回答这个问题,it would be preferable 在这里包含答案的基本部分,并提供链接以供参考。
【解决方案2】:

如果您想在另一个 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");
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-24
    • 2020-08-16
    • 1970-01-01
    • 2017-10-12
    • 2010-09-23
    • 1970-01-01
    相关资源
    最近更新 更多