如何将外部 JavaScript 文件放入我的 HTML 文档中
how do i put an external javascript file into my html document?
对于作业,我需要编写一个代码来按字母顺序显示数组并计算数组中的项目。我可以很好地做到这一点,但最后一个要求是将 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="文件位置"应该是文件所在位置的相对/绝对路径。
相关文章:
- 无法将数据从firebase获取到我的html页面
- 我的HTML按钮没有在Javascript中运行
- 我的html有一些错误
- 为什么jquery悬停在jsfiddle中可以工作,而在我的html布局中却不能
- 为什么<p>没有插入到我的html中
- 如何在我的html网页中使用jquery自动完成
- <text区域>在我的html中包含event.keycode==13之后,wrap就不起作用了
- 我的html表单无法验证.请参阅代码片段中的html代码和java脚本
- 如何重定向到我的html网站youtube嵌入视频打开在youtube应用程序
- 为什么我的html页面没有在<ui视图>
- 在将javascript附加到我的html中时遇到问题
- 为什么我的HTML标签消失了
- 使用 JavaScript 在我的 html 页面中放大图像
- 如何在javascript中调用onclick事件?我没有'我不想在我的HTML页面中使用任何事件
- 我的HTML、CSS和Javascript应该放在一起还是分开
- 为什么我的HTML似乎无法访问我的javascript
- 如何使用 javascript 向我的 html 添加内容而不擦除整个页面
- 如何为我的 html 表单制作打印预览和打印按钮
- 无法将我的 html 文档连接到 jquery
- JavaScript函数不适用于我的HTML表单