单击按钮更改日期

change day by clicking on button

我希望每次单击按钮时都能看到 下一个 day from day 数组列表

我能得到答案的唯一方法是 Math.random() 每次单击按钮时都有不同的结果,但我希望每次单击它时都能在第二天显示给我.

function day() {
  var days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
  document.getElementById("demo").innerHTML = days[Math.floor(Math.random() * 7)];
}
<button onclick='day()'>Click to see</button>
<span id="demo"></span>

let index = Math.floor(Math.random() *7); //if you want always start from 'Monday' you can use 0 as startIndex
let days =['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
function day(){      
  document.getElementById("demo").innerHTML = days[index];
  index = (index+1)%7     
}
<button onclick='day()'>Click to see</button>
<h1 id="demo"></h1>

您可以保留一个数组来表示一周中的几天,同时还保留一个索引来显示当前日期 current

每次点击都会增加 current 值。 innerHtml 值将是当前索引(添加 % 以防止跳出)

var days =['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];
let current = 0;
function day(){
    document.getElementById("demo").innerHTML = days[current++ % days.length];
}
<button onclick='day()'>Click to see</button>
<div id="demo">

</div>

从今天开始,您可以使用星期日开始的 getDay

const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
let day = new Date().getDay(); //today
document.getElementById('addDay').addEventListener('click', function() {
  document.getElementById("demo").innerHTML = days[day++ % 7]; // move the ++ to ++day to show tomorrow on first click
})
<button id="addDay" type="button">Click to see</button>
<span id="demo"></span>