我正在使用普通的javascript构建我的小日历(所以请不要jquery)我很难进行上个月的显示 到目前为止,这是我上个月获得的代码:
document.getElementById("prev-month").addEventListener("click", function(e) {
console.log('first', prevMonth);
prevMonth = monthNamesArray[currentMonth - 1]; //Array with all the month labels like ['Jan', 'Feb', 'Mar'];
month.innerHTML = '<td>'+ prevMonth +'</td>'; //Here i replace the html cell where the month is display
console.log('second', prevMonth);
});
两个调试器的console.log是: 首次点击:第一个未定义的第二个九月(上个月) 第二次点击:9月9日第一次
为什么在第二次点击期间第二个控制台日志没有成为8月的第二个? 为什么prevMonth回归一个月?
非常感谢任何帮助,特别是解释,
答案 0 :(得分:1)
您没有更新currentMonth
,仍然指向october
。
答案 1 :(得分:1)
您是否有任何理由需要prevMonth,为了保持正确更新,您最好将其写为:
currentMonth = monthNamesArray[(currentMonth==0)? 11 : currentMonth-1];
三元运算符确保您在1月份不会转到monthNamesArray[-1]
,而是回到monthNamesArray[11]
。
编辑: 两个方向,方向变量可以是任何大小的整数值,所以你可以去方向= -2,它将向后2个月。 currentMonthIndex是当前月份0到11的索引。
var remainder = (currentMonthIndex + direction) % 12;
currentMonth = monthNamesArray[Math.floor(remainder >= 0 ? remainder : remainder + 12)];