我想以下列格式显示日期和日期,但它对我不起作用。显示“Uncaught TypeError:无法设置属性'innerHTML'为null”时出错。任何人都可以让我脱离这个吗?
输出: -
今天是:星期三
当前时间是:晚上8点:25:20
**我的HTML代码: - **
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Excercise</title>
<script src="Js\DateTimeExcercise.js">
</script>
</head>
<body>
Today is : <span id="day"></span>
<br/><br/>
Current time is : <span id="time"></span>
</body>
</html>
**我的Java脚本代码: - **
var day, time, Sec, Min, Hr, AMPM;
AMPM = "AM";
day = new Date().getDay();
Sec = new Date().getSeconds();
Min = new Date().getMinutes();
Hr = new Date().getHours();
if (Hr>12)
{
Hr = Hr - 12;
AMPM = "PM";
}
switch(day)
{
case 0:
txt = "Sunday";
break;
case 1:
txt = "Monday";
break;
case 2:
txt = "Tueday";
break;
case 3:
txt = "Wednesday";
break;
case 4:
txt = "Thrusday";
break;
case 5:
txt = "Friday";
break;
case 6:
txt = "Saturday";
break;
}
document.getElementById("day").innerHTML = txt;
document.getElementById("time").innerHTML = Hr + " "+ AMPM + " "+ ":" + Min + ":" + Sec;
答案 0 :(得分:2)
在呈现DOM之前加载脚本。因此,最好将脚本标记放在所有代码下方,就在body标记的上方。现在代码无法找到元素
另一种可能性是将代码包装在事件监听器中,如下所示:
document.addEventListener("DOMContentLoaded", function()
// your code
});