如何将外部 JavaScript 文件放入我的 HTML 文档中

how do i put an external javascript file into my html document?

本文关键字:我的 HTML 文档 文件 外部 JavaScript      更新时间:2023-09-26

对于作业,我需要编写一个代码来按字母顺序显示数组并计算数组中的项目。我可以很好地做到这一点,但最后一个要求是将 JavaScript 放入外部文件中。我该怎么做?下面是我的代码以及我需要放入外部文件的内容,但我不知道该怎么做。

这是完成的代码,但我需要脚本标签中的所有内容都在外部文件中

<!DOCTYPE html>
<html>
<head></head>
<body>
   <h2>Question 2 Array</h2>
   <p id="array"></p>
   <button onclick="alpha()">Sort alphabetically</button>
   <button onclick="count()">Count items in array</button>
   <script>
   var products = [" Printer", " Tablet", " Router", " Keyboard", " Mouse", " PC"];
   document.getElementById("array").innerHTML = products;
   function alpha() {
      document.getElementById("array").innerHTML = products.sort();
   }
   function count() {
      document.getElementById("array").innerHTML = products.length;
   }
   </script>

</body>
</html>

只是为了缩小它的范围,这里是要去外部的事情。

 var products = [" Printer", " Tablet", " Router", " Keyboard", " Mouse", " PC"];
     document.getElementById("array").innerHTML = products;
     function alpha() {
        document.getElementById("array").innerHTML = products.sort();
     }
     function count() {
        document.getElementById("array").innerHTML = products.length;
     }

把你的代码放在myFile中.js并将这个文件链接到你的HTML文件,就像这样:

<script src="myFile.js" type="text/javascript"></script>
<!DOCTYPE html>
<html>
<head>
<script src="path_to_external_file"></script> <!-- here comes your javascript file path -->
</head>
<body>
</body>
</html>

这真的很简单

<script src="path to your .js file"></script>

例如,创建一个名为 site 的 JS 文件。那么你的js文件应该是site.js。把你所有的javascript代码放在那个文件中。

然后在所有 css 之后用 html <head> 调用它。请记住,如果您使用的是jQuery,请将js文件放在jquery包含之后。

<script src="../js/yourjavascriptfile.js"></script>

放入一个.js文件并将其链接到 head 标签中,src="文件位置"应该是文件所在位置的相对/绝对路径。