2017-06-27 35 views
0

我正在創建一個日曆應用程序,現在我正在努力讓自己的日子充滿活力。每個月與每週的正確日期對齊?

到目前爲止在後端,我有一個數組,它給了我每個月的天數。

const DaysInEachMonth = [ 
    moment('2017-01').daysInMonth(), 
    moment('2017-02').daysInMonth(), 
    moment('2017-03').daysInMonth(), 
    moment('2017-04').daysInMonth(), 
    moment('2017-05').daysInMonth(), 
    moment('2017-06').daysInMonth(), 
    moment('2017-07').daysInMonth(), 
    moment('2017-08').daysInMonth(), 
    moment('2017-09').daysInMonth(), 
    moment('2017-10').daysInMonth(), 
    moment('2017-11').daysInMonth(), 
    moment('2017-12').daysInMonth() 
]; 

在我的ejs文件中,我使用DaysInEachMonth來遍歷天數。

<ul id="days"> 
<% for(var i = 0; i <= 11; i++) { %> 
    <% var n = DaysInEachMonth[i] %> 
    <% for(var j=1; j <= n; j++) { %> 
     <li> <%= j %> </li> 
     <% } %> 
<% } %> 
</ul> 

現在我遇到的問題是每個月的所有日子都在一月份之下顯示。我如何做到這一點,每次我按下一個按鈕去下個月,我的日子也會改變。也許這不是做這件事的最好方式。任何幫助都會很棒,你可以看到我是Node新手。

+2

這是真的很難幫你,因爲你在做什麼,是不是我會親自做的所有。所以從技術上講,您需要使用CodePen或類似的東西向我們展示工作代碼。我會親自創建一個代表一個月的視圖,並在每次滑到兩側時呈現新視圖,然後將其附加到隱形區域 - 一次提前一個月。換句話說 - 一次預裝一個月。 – Alexus

回答

1

我不得不同意@Alexus;這不是我親自做的事情。

但要回答你的問題,moment.js有強大的方法來操縱日期。例如,moment#month(number|String)可以改變月份。並利用這一點,你可以不喜歡我在下面的代碼片段所做的:

// Let's just set `nthMonth` to the 10th month for this example. 
 
var nthMonth = 10; 
 
// This gets the month November. (the tenth month when starting from 0) 
 
var month = moment().month(nthMonth); 
 
// This gets the amount of days in November 
 
var daysInMonth = month.daysInMonth(); 
 
// Using the moment#format function, we can get a human-readable string from the date. 
 
// By using the format 'MMMM', we only get the name of the month. 
 
var monthName = month.format('MMMM') 
 

 
console.log('Moment.JS Example:'); 
 
console.log(' Nth month:', nthMonth) 
 
console.log('Name of month:', monthName) 
 
console.log('Days in month:', daysInMonth)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>

這也適用於你的代碼。 EJS不StackOverflow的片段支持,但我認爲你可以看到它是如何工作的:

// And just for your code: 
 
var m = moment(); 
 
var days = $('#days'); 
 
for (var i = 0; i < 11; i++) { 
 
    m.month(i); 
 
    days.append(`<li class="month">${m.format('MMMM')}</li>`); 
 

 
    var n = m.daysInMonth(); 
 
    for (var j = 1; j <= n; j++) { 
 
    // We could use this code to show only the numbers. 
 
    //days.append(`<li>${j}</li>`); 
 
    // Or we use this code to make it a bit fancier. 
 
    days.append(`<li>${m.date(j).format('dddd Do')}</li>`); 
 
    } 
 
}
#days > li { 
 
    list-style-type: none; 
 
} 
 

 
.month { 
 
    font-weight: bold; 
 
    margin-top: .5em 
 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<ul id="days"> 
 
</ul>