根据一天中的时间转到新的 html 文件

Go to a new html file depending on time of day

本文关键字:html 文件 时间 一天      更新时间:2023-09-26

我对JavaScript很陌生,所以我想知道你们中是否有人可以解决这个难题。这显然是完全错误的,但希望您能看到我需要什么。我需要索引.html根据一天中的时间重定向到新的.html文件。

function getIndex() {
var currentTime = new Date().getHours();
if (0 <= currentTime&&currentTime < 5) {
document.write("night.html");
}
if (5 <= currentTime&&currentTime < 11) {
document.write("morning.html");
}
if (11 <= currentTime&&currentTime < 16) {
document.write("day.html");
}
if (16 <= currentTime&&currentTime < 22) {
document.write("evening.html");
}
if (22 <= currentTime&&currentTime <= 24) {
document.write("night.html");
}
}
getIndex();

这是另一种做事的方式。

function getIndex() {
    var d = new Date();
    var h = d.getHours();
    var pages = ['night', 'morning', 'day', 'evening', 'night'];
    var eTimes = [0, 5, 11, 16, 22, 24];
    for (var i = 0; i < eTimes.length - 1; i++) {
        if (eTimes[i] <= h && h < eTimes[i + 1]) {
            window.location.href = pages[i] + '.html';
        }
    }
}
getIndex();

您只需要使用window.location.href重定向页面

function getIndex() {
  var currentTime = new Date().getHours();
  if (0 <= currentTime&&currentTime < 5) {
      window.location.href = 'night.html';
  } else if (5 <= currentTime&&currentTime < 11) {
      window.location.href = 'morning.html';
  } else if (11 <= currentTime&&currentTime < 16) {
     window.location.href = 'day.html';
  } else if (16 <= currentTime&&currentTime < 22) {
    window.location.href = 'evening.html';
  } else if (22 <= currentTime&&currentTime <= 24) {
    window.location.href = 'night.html';
  }
}
getIndex();

休息所有你的代码都很好