2015-06-28 89 views
1

我已成功管理(在堆棧溢出的幫助下)循環從2015年5月開始直到2015年結束的日曆。現在我想突出顯示當前日期是6月28日星期日。但由於某些原因,它突出了錯誤的日期,我不認爲它是因爲代碼,但我不是100%確定。我突出顯示當前通過JavaScript的日期顯示不正確

結帳這個鏈接看到它在視覺上(http://gyazo.com/30e448d0f84c8f1c55e4dd1ce6d91f38

的jsfiddle鏈接:https://jsfiddle.net/GY22/vqfk8yLL/

這是我的html代碼:

<ul id="timeline"> 
    <li></li> 
</ul> 

這是我的javascript代碼:

<script> 

// Get today's current date. 
var now = new Date(); 
console.log(now); 

// Calculates the number of the week 
var weekNumber = ((now.getDate()<10) ? "0" : "")+ now.getDate(); 
console.log("The current week number is: " + weekNumber); 

// Array list of months. 
var month = new Array(12); 
month[0] = "January"; 
month[1] = "February"; 
month[2] = "March"; 
month[3] = "April"; 
month[4] = "May"; 
month[5] = "June"; 
month[6] = "July"; 
month[7] = "August"; 
month[8] = "September"; 
month[9] = "October"; 
month[10] = "November"; 
month[11] = "December"; 
//console.log(month[3]); 

var weekDay = new Array(7); 
weekDay[0]= "Su"; 
weekDay[1] = "Mo"; 
weekDay[2] = "Tu"; 
weekDay[3] = "We"; 
weekDay[4] = "Th"; 
weekDay[5] = "Fr"; 
weekDay[6] = "Sa"; 

function formatDate(date) { 
    var month = date.getUTCMonth() +1; 
    var dayNumber = date.getUTCDate(); 
    var year = date.getUTCFullYear(); 
    var day = date.getUTCDay(); 
    return weekDay[day] + ": " + dayNumber + "-" + month + "-" + year + "; "; 
    //return weekDay[day] + " " + dayNumber + "; "; 
} 
//console.log(formatDate(new Date())); 

var today 

function addListItem(){ 
    var createListItem = document.createElement("li"); 
    var outputListItem = document.createTextNode(today); 

    createListItem.appendChild(outputListItem); 
    var createUl = document.getElementsByTagName("ul"); 
    createUl[0].appendChild(createListItem); 
} 

// loop starting from may up untill for months from the set date 
for (var i = 0; i < 122; i++){ 
    today = formatDate(new Date(2015, 05, i)); 
    //document.write(today + "<br />"); 
    addListItem(); 
} 

document.getElementById('timeline'). 
getElementsByTagName('li')[(new Date()).getDate() - 1].className += ' currentDate'; 

回答

1

更改從最後一行:

getElementsByTagName('li')[(new Date()).getDate() - 1].className += ' currentDate'; 

要:

getElementsByTagName('li')[(new Date()).getDate() + 1].className += ' currentDate'; 

日期出現通過的前一天被關閉,這樣應該修復它。

+0

Hoegan,我必須做+2,但它正在做我現在想要的;-) – GY22

+0

這整行代碼沒有意義。爲什麼你使用月份的一天作爲索引選擇器?當前選擇的日期將會越來越多地抵消每天。 – NGPixel

+0

@NGPixel,不知道如何實現我想要的,這就是爲什麼我這樣做,但如果你有更好的解決方案,我將不勝感激 – GY22

0

請考慮使用MomentJS。它會爲您節省大量的代碼和日期的問題:

http://momentjs.com/

如果您希望將自己的代碼,將您addListItem內的當前日期邏輯()方法。

if(today == formatDate(new Date())) { 
    createListItem.className += ' currentDate'; 
} 
+0

我想突出顯示當前日期,但由於某些原因突出顯示星期五25日 – GY22

+0

我將您的代碼添加到AddListItem()方法,但它不遍歷所有日期。檢查此jsfiddle https://jsfiddle.net/GY22/vqfk8yLL/1/ – GY22

+0

嘗試編輯的代碼。第一個變量已經格式化。 – NGPixel