我目前正在尝试使用 html 和外部 javascript 文件构建网页。 javascript 文件名为“main.js”,与 html 文件位于同一目录中。我想从 html 文件中的 javascript 文件调用一个函数。
该函数链接到使用以下行调用的按钮:
<button onclick="myFunc()">Click Me</button>
如果我使用脚本标记并将 javascript 嵌入到 html 文件中,它可以正常工作,格式为:
<script>
funtion myFunc(){
//Code here
}
</script>
当我将此函数放在单独的 main.js 文件中,然后使用
<script type="text/javascript" src="/main.js"></script>
按钮什么也不做。有没有我缺少的语法?
添加编辑:
这是并进行编辑以希望使问题更清楚。我是 javascript 的初学者,所以如果我以一种不清楚的方式提问,我深表歉意。下面是我在 html 文件中用来测试的完整 javascript 函数。它来自w3学校,我只是用它来测试。该函数将一个正方形从较大正方形的左上角移动到右下角。
<script>
function myMove() {
var id = null;
var elem = document.getElementById('myAnimation');
var pos = 350;
clearInterval(id);
id = setInterval(frame,10);
function frame() {
if (pos == 0){
clearInterval(id);
} else {
pos--;
elem.style.bottom = pos +'px';
elem.style.right = pos + 'px';
}
}
}
</script>
当直接嵌入到 html 代码中时,它工作得很好。当我把这个确切的函数放在一个名为“test.js”的外部 javascript 文件中,然后在 html 中包含对该文件的引用,所以 html 文件的主体是:
<script type="module" src="/test.js"></script>
<a href="../index.html"><button1>home</button1></a><br>
<button onclick="myMove()">Click Me</button>
<div id ="myContainer">
<div id ="myAnimation"></div>
</div>
作为参考,javascript 文件如下所示:
import './style.css'
function myMove() {
var id = null;
var elem = document.getElementById('myAnimation');
var pos = 350;
clearInterval(id);
id = setInterval(frame,10);
function frame() {
if (pos == 0){
clearInterval(id);
} else {
pos--;
elem.style.bottom = pos +'px';
elem.style.right = pos + 'px';
}
}
}
什么都没发生。这是否使问题更清楚?
回答1
我这样做了,它对我有用(文件是分开的)
function myFunc() {
alert("hello")
}
<html>
<head>
</head>
<body>
<h1> Testing... </h1>
<button onclick="myFunc()"> Click Me </button>
<script src="./main.js"></script>
</body>
</html>
在简单的 python 服务器中运行代码也是一个好主意。 https://linuxconfig.org/running-a-simple-http-web-server-with-one-terminal-command-and-python