簡體   English   中英

如何將 Javascript 文件鏈接到另一個 Javascript 文件

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

這里有兩個文件在同一個文件夾中。 我正在嘗試在app2調用一個名為greet of app1的函數。

應用程序1.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 文件而不是嵌入的<script>標簽,但這也許會有所幫助

如何在另一個js文件中包含js文件?

如果要在另一個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>

然后,使用第一個文件

文件1.js

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

文件2.js

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM