gpt4 book ai didi

javascript - 如何使用javascript改变当前变量?

转载 作者:行者123 更新时间:2023-11-28 11:30:58 24 4
gpt4 key购买 nike

我有一个小的 html 页面,如果用户单击其中一个按钮,它将更改日期。我有一个功能,它显示今天是星期几,但我希望用户能够按“>”,这会将日期从今天更改为第二天。如果按“<”,则为前一天。我不完全确定现在应该如何进行。

var date = new Date();
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
document.getElementById("todayField").innerHTML = days[date.getDay()];

function next() {
var date = new Date();
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
document.getElementById("todayField").innerHTML = days[date.getDay()];

if (btnNext.click) {
days++;
document.getElementById("todayField").innerHTML = days[date.getDay()];
}
}

function prev() {
var date = new Date();
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
document.getElementById("todayField").innerHTML = days[date.getDay()];

if (btnNext.click) {
days--;
document.getElementById("todayField").innerHTML = days[date.getDay()];
}
}
<p>Click to change day</p>
<button type="button" name="btnPrev" onclick="next()"><</button>
<button type="button" name="btnNext" onclick="prev()">></button>
<p id="todayField"></p>

感谢所有帮助!

最佳答案

我给你准备了一把 fiddle :https://jsfiddle.net/k8g1mros/

这背后的逻辑是:

var date = new Date();
var index = date.getDay();

function prev() {
var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var nextIndex = index - 1 < 0 ? 6 : index-1;
index = nextIndex
console.log(nextIndex)
document.getElementById("todayField").innerHTML = days[nextIndex];
}
document.getElementById("prev").addEventListener("click", function() {
prev();
})

一些解释:

首先,您可以使用 var index=date.getDay() 获取实际日期。通过单击下一个上一个此索引将向上/向下计数。一旦到达 0(周日)或 6(周六),索引将重置为 0/6

这发生在这里(对于上一个):

var nextIndex = index - 1 < 0 ? 6 : index-1;

这称为内联条件。进一步阅读:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

How to write an inline IF statement in JavaScript?

这相当于:

var nextIndex = 0
if (index - 1 < 0 ) {
nextIndex = 0
} else {
nextIndex = index - 1
}

现在你明白背后的逻辑了吗?

关于javascript - 如何使用javascript改变当前变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48565647/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com