嗨,我收到了这段代码,根据一天中的时间显示了不同的消息,但仅显示0以后的消息。有人知道我在做什么吗?
JS
var today = new Date();
var time = today.getHours();
var greet;
if (time > 0) {
greet = 'text 1';
} else if (time > 12) {
greet = 'Good afternoon Sir!';
} else if (time > 18) {
greet = 'Good evening babe!';
} else {
greet = 'yo shits broken yo!';
}
var show = document.getElementById('message');
show.textContent = greet;
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="Productiviteits website voor eigen gebruik :) ">
<meta name="keywords" content="HTML,CSS,JavaScript">
<meta name="author" content="Jeroen Renema">
<!-- Title -->
<title>Productivity Library</title>
</head>
<body>
<h2 id="message">hey</h2>
<script src="js/Welcome.js"></script>
</body>
</html>
答案 0 :(得分:2)
考虑一下if
的顺序。第一个匹配条件将被执行。并且> 0
将被匹配,即使该值为> 12
或> 18
。因此,只需更改顺序即可。 ;)
我建议将最后一张支票更改为time >= 0
,因为如果某人在午夜之后访问此页面,则将显示文本yo shits broken yo!
直到其为1 o'clock
。
var today = new Date();
var time = today.getHours();
var greet;
if (time > 18) {
greet = 'Good evening babe!';
} else if (time > 12) {
greet = 'Good afternoon Sir!';
} else if (time >= 0) {
greet = 'text 1';
} else {
greet = 'yo shits broken yo!';
}
var show = document.getElementById('message');
show.textContent = greet;
<h2 id="message">hey</h2>
答案 1 :(得分:0)
您的比较还应在以下条件的值上包含&&
,以使其正常工作。当前time > 0
始终是true
,无论time
的值是多少,它都需要大于0
,因此要使它起作用,请添加and
条件
var today = new Date();
var time = today.getHours();
var greet;
if (time > 0 && time <= 12) {
greet = 'text 1';
} else if (time > 12 && time <= 18) {
greet = 'Good afternoon Sir!';
} else if (time > 18 && time <= 24) {
greet = 'Good evening babe!';
} else {
greet = 'yo shits broken yo!';
}
var show = document.getElementById('message');
show.textContent = greet;
<h2 id="message">hey</h2>