2014-10-05 39 views
0

我正在建立我的小日曆與純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是: 首先點擊:第一未定義第二九月(比上月) 第二點擊:第一九月第二月

爲什麼在第二點擊第二個控制檯日誌沒有成爲第二個八月? 爲什麼prevMonth只會回到一個月?

任何幫助,特別的解釋,是真正的讚賞

回答

1

你沒有更新currentMonth,仍然指向october

+0

啊哈!謝謝!我怎麼看不到它! – 2014-10-05 20:18:58

1

是否有任何理由爲什麼你需要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)]; 
+0

酷!那是我的下一步! :) – 2014-10-06 07:13:34