[英]I can't figure out what I'm doing wrong with getDay()
I wanted the page to detect if it was Thursday, and if it was display some text.我希望页面能够检测今天是否是星期四,以及是否显示一些文本。 I don't understand why this won't work.
我不明白为什么这行不通。 Is it because I can do = on a if than?
是因为我可以在 if 上做 = 吗? Please explain, thank you!
请解释一下,谢谢!
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<p id="bleh"></p>
<script>
var day;
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
document.getElementById("demo").innerHTML = "Today is " + day;
</script>
<p id="bleh"></p>
<script>
function myFunction() {
if(new Date().getDay() == 4)
document.getElementById("bleh").innerHTML = "Check your grades.";
}
}
</script>
</body>
</html>
The part thats not working is this one:不起作用的部分是这个:
<script>
function myFunction() {
if(new Date().getDay() == 4)
document.getElementById("bleh").innerHTML = "Check your grades.";
}
}
</script>
PS I would use OnTime, but I am host my webpage off of github pages so I can't load it on there, this is why I'm working with this type of JS. PS 我会使用 OnTime,但我将我的网页托管在 github 页面之外,所以我无法在那里加载它,这就是我使用这种类型的 JS 的原因。
if (day = 4;) {
Notice the single =
where you should be using ==
or ===
.请注意您应该使用
==
或===
的单个=
。 Also remove the semicolon:还要去掉分号:
if (day === 4) {
Also , as pointed out in the comments, you should be checking the day as a string, since that's what you set it to!此外,正如评论中所指出的,您应该将日期作为字符串检查,因为这就是您设置的内容!
if (day === "Thursday") {
would not it be better to store your day names in an array like this将您的日期名称存储在这样的数组中不是更好吗
var days = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
];
function getCurrentDayName (dayIndex) {
return days[dayIndex];
}
console.log(getCurrentDayName (new Date ().getDay()))
You can get the name of day much easier like this:您可以像这样更轻松地获取日期名称:
let today = new Date() demo.innerHTML = `Today is ${new Intl.DateTimeFormat('en-US', {weekday: 'long'}) .format(today)}`; let toDay = today.getDay() bleh.innerHTML = toDay === 4 ? 'Check your grades.' : `Not Thursday. Come back in ${(11 - toDay) % 7} days to re-check.`
<p id="demo"></p> <p id="bleh"></p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.