我正在创建一个网站,该网站将根据用户的一天中的时间显示夜晚,下午或早晨的图像。
但是看起来,由于在标记"onload="
中使用<body>
调用函数时出现语法错误,因此JS无法正常工作。我的VS Code Javascript higlighter无法在文字窗口,文档或getElementById上运行。
我的JS哪一部分可能是错误的?
这是HTML
<!DOCTYPE html>
<html lang="pt-br">
<head>
<script type="javascript" src="/script.js"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie-edge">
<link rel="stylesheet" href="/style.css">
</head>
<body onload="load()">
<section>
<div id="msg">
Message here
</div>
<div id="foto">
<img id="image" src="img/afternoon.png">
</div>
</section>
<footer>
<p>© Koala</p>
</footer>
</body>
</html>
这是JSfunction load(){
var msg = window.document.getElementById('msg');
var img = window.document.getElementById('image');
var dt = new.Date();
var hour = dt.getHours();
msg.innerHTML = 'Now it is ${hour} hours.';
if (hour>= 0 && hour < 12) {
img.src = 'img/morning.png';
} else if (hour => 12 && hour < 18) {
img.src = 'img/afternoon.png';
} else {
img.src = 'img/night.png';
}
}
PS:我尝试过在Mozilla和Chrome上运行它。没有成功
最佳答案
错误似乎与以下行有关:
var dt = new.Date();
要实例化一个新的Date对象,您需要使用以下语法:var dt = new Date();
解决此语法错误后,应正确加载JS文件,然后onload
属性将能够触发load
函数。这是一个工作示例:https://codesandbox.io/s/stack-overflow-onload-8opgp?file=/script.js
关于javascript - 未捕获的ReferenceError : load is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63096685/