我想在我的网站上的一些div中添加5个即将到来的日期名称。我为日名创建了数组,然后我从中调用了值并添加了天数。该方法仅适用于第一天,然后数组结束,从第2天到第5天它回应“未定义”。
请帮忙吗?
var weekday=new Array(7);
weekday[0]="Nedelja";
weekday[1]="Ponedeljek";
weekday[2]="Torek";
weekday[3]="Sreda";
weekday[4]="Četrtek";
weekday[5]="Petek";
weekday[6]="Sobota";
var dan = weekday[today.getDay()];
var dan_1 = weekday[today.getDay()+1];
document.getElementById("day1").innerHTML = dan_1;
var dan_2 = weekday[today.getDay()+2];
document.getElementById("day2").innerHTML = dan_2;
var dan_3 = weekday[today.getDay()+3];
document.getElementById("day3").innerHTML = dan_3;
var dan_4 = weekday[today.getDay()+4];
document.getElementById("day4").innerHTML = dan_4;
var dan_5 = weekday[today.getDay()+5];
document.getElementById("day5").innerHTML = dan_5;
谢谢你们!
答案 0 :(得分:2)
嗯,你需要%7和7(一周中的天数)
var weekday=new Array(7);
weekday[0]="Nedelja";
weekday[1]="Ponedeljek";
weekday[2]="Torek";
weekday[3]="Sreda";
weekday[4]="Četrtek";
weekday[5]="Petek";
weekday[6]="Sobota";
var dan = weekday[today.getDay()%7];
var dan_1 = weekday[(today.getDay()+1)%7];
document.getElementById("day1").innerHTML = dan_1;
var dan_2 = weekday[(today.getDay()+2)%7];
document.getElementById("day2").innerHTML = dan_2;
var dan_3 = weekday[(today.getDay()+3)%7];
document.getElementById("day3").innerHTML = dan_3;
var dan_4 = weekday[(today.getDay()+4)%7];
document.getElementById("day4").innerHTML = dan_4;
var dan_5 = weekday[(today.getDay()+5)%7];
document.getElementById("day5").innerHTML = dan_5;
例如:如果today.getDay()
返回5,则接下来的5天是10,这在您的数组中不存在。当你%7时,你会回到3(下周)
答案 1 :(得分:1)
您可以在数组访问中添加模%
运算,以防止溢出并在开头重新启动:
// ...
var dan_1 = weekday[(today.getDay()+1)%7];
document.getElementById("day1").innerHTML = dan_1;
var dan_2 = weekday[(today.getDay()+2)%7];
document.getElementById("day2").innerHTML = dan_2;
var dan_3 = weekday[(today.getDay()+3)%7];
document.getElementById("day3").innerHTML = dan_3;
var dan_4 = weekday[(today.getDay()+4)%7];
document.getElementById("day4").innerHTML = dan_4;
var dan_5 = weekday[(today.getDay()+5)%7];
document.getElementById("day5").innerHTML = dan_5;
答案 2 :(得分:0)
你的问题是以合乎逻辑的方式推进这一天。这是通过添加到当前日期并从除法中选择余数(模数,%
)来实现的。请参阅下面代码中的(dan + i) % 7
部分。
我将使用Khanh TO’s answer中已修复的代码并以更简洁的方式编写代码。现在你的代码有点重复,这可以通过使用数组文字和循环来帮助。
var today = new Date();
var weekday = ["Nedelja","Ponedeljek","Torek","Sreda","Četrtek","Petek","Sobota"];
var dan = today.getDay();
for (var i = 1; i <= 5; i++) {
var elem = document.getElementById("day" + i);
elem.innerHTML = weekday[(dan + i) % 7];
}
我相信看到更优雅的风格对你有好处。