我正在用普通的javascript (所以请不要使用jquery)构建我的小日历,到目前为止,我很难让prev月份显示--这是我的get前一个月的代码:
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月1日第二次9月
为什么在第二次单击期间,第二次控制台日志没有成为第二次8月?为什么prevMonth只追溯到一个月前?
任何帮助,特别是一个解释,都是非常感谢的。
发布于 2014-10-05 20:17:20
您没有更新currentMonth,仍然指向october。
发布于 2014-10-05 20:29:39
是否有任何理由需要prevMonth,为了保持它的正确更新,您最好将它写成:
currentMonth = monthNamesArray[(currentMonth==0)? 11 : currentMonth-1];三元运算符确保在一月时不会转到monthNamesArray[-1],但是它会被包装回monthNamesArray[11]。
编辑:两个方向,方向变量可以是任意大小的整数值,所以您可以选择方向= -2,它将向后移动2个月。currentMonthIndex是当前月份0到11的指数。
var remainder = (currentMonthIndex + direction) % 12;
currentMonth = monthNamesArray[Math.floor(remainder >= 0 ? remainder : remainder + 12)];https://stackoverflow.com/questions/26206742
复制相似问题