gpt4 book ai didi

javascript - 在 Javascript 的 if 语句中更改变量的值

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:18:15 25 4
gpt4 key购买 nike

我在处理一段代码时遇到了问题,这让我抓狂。我已经坚持了几个小时,最糟糕的是我假设它真的很简单;我就是想不通。

我正在尝试使用 Javascript/jQuery 制作一个简单的事件日历。这是我的简化代码:

var currentMonth = 1;
if (currentMonth == 1) {
$("#prev-month").click( function() {
currentMonth = 12;
});
$("#next-month").click( function() {
currentMonth = 2;
});
}
if ( currentMonth == 2) {
$("#prev-month").click( function() {
currentMonth = 1;
});
$("#next-month").click( function() {
currentMonth = 3;
});
}
if ( currentMonth == 3) {
$("#prev-month").click( function() {
currentMonth = 2;
});
$("#next-month").click( function() {
currentMonth = 4;
});
}
if ( currentMonth == 4) {
$("#prev-month").click( function() {
currentMonth = 3;
});
$("#next-month").click( function() {
currentMonth = 5;
});
}

现在,每次我点击 ID 为“next-month”的按钮时,它总是 2。如果我点击 ID 为“prev-month”的按钮,它总是 12。它永远不会改变。我做错了什么?

最佳答案

您的脚本代码只运行一次。单击处理程序后不会更改它们,因此这些处理程序将始终提供相同的结果。

但是与其解决这个问题,不如为每个按钮使用一个处理程序并使用算术计算下一个月/上个月而不是在运行时更改 12 个处理程序。

$("#prev-month").click( function() {
currentMonth = (currentMonth - 1) || 12;
});
$("#next-month").click( function() {
currentMonth = currentMonth % 12 + 1;
});

关于javascript - 在 Javascript 的 if 语句中更改变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9658312/

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