在使用过程中,制作了一个demo,使用getTime()方法制作了一个问候语,原代码在编写完成后发现无法成功打印出预想结果,只是做出了button按钮,但是按钮按下并没有反应。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>候语句</title>
<script type="text/javascript">
window.function(){
function timeDemo(){
var a;
var time=new Date().getHours();
if (time<12) {
a="早上好!";
} else if(time<14){
a="中午好!";
} else if(time<18){
a="下午好!";
} else if(time<22){
a="晚上好!";
} else {
a="夜深了,注意休息!";
}
document.getElementById("time").innerHTML=a;
}
}
</script>
</head>
<body>
<button onclick="timeDemo()">点击获取问候语</button>
<p id="time"></p>
</body>
</html>
由于使用了window.onload仍旧无法优先读取body当中的内容,于是使用了把js写进body里面的方法,得出以下代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>候语句</title>
</head>
<body>
<button onclick="timeDemo()">点击获取问候语</button>
<p id="time"></p>
<script type="text/javascript">
/* 放在head处,即使使用了window.onload一样无法打印成功
因此只能把这个script移到body当中*/
//window.function(){
function timeDemo(){
var a;
var time=new Date().getHours();
if (time<12) {
a="早上好!";
} else if(time<14){
a="中午好!";
} else if(time<18){
a="下午好!";
} else if(time<22){
a="晚上好!";
} else {
a="夜深了,注意休息!";
}
document.getElementById("time").innerHTML=a;
}
// }
</script>
<!-- <button onclick="timeDemo">点击获取问候语</button>
<p id="time"></p> -->
</body>
</html>
测试成功。
个人观点:该问题应该是JavaScript找不到页面元素,因此加载失败。
往下使用js会把js写在HTML较为靠后的地方,以方便JavaScript找到页面元素