2016-10-05 51 views
0

我有這個片段來驗證,如果數據日期屬性是比當前日期更新/相等/舊比較分配相應的類。但是,該代碼僅適用於1-9,否則將被視爲比當前日期更早。驗證並將類添加到jQuery的過去,當前和將來的日期

請參閱這些代碼

$(function() { 
    var date = new Date(), 
    currentDate = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate(); 
    $(".grid-item").each(function() { 
    var specifiedDate = $(this).data('date'); 
    if (specifiedDate == currentDate) { 
     $(this).addClass('today'); 
    } else if (currentDate > specifiedDate) { 
     $(this).addClass('past'); 
    } else { 
     $(this).addClass('future'); 
    } 
    }); 
}); 

請參閱此工作提琴。感謝您的幫助!

https://jsfiddle.net/sandalkoyak/jrnvzrfu/

回答

0

試試這個代碼。您需要使用Date.parse()方法解析日期字符串,如果該字符串無法識別,或者在某些情況下包含非法日期值(例如2015年,自1970年1月1日,00:00:00 UTC或NaN返回毫秒-02-31)。

$(function() { 
    var date = new Date(), 
    currentDate = date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDate(); 
    currentDate=Date.parse(currentDate); 
    $(".grid-item").each(function() { 
     var specifiedDate = $(this).data('date'); 
     specifiedDate=Date.parse(specifiedDate); 
     if (specifiedDate == currentDate) { 
     $(this).addClass('today'); 
     }else if (currentDate > specifiedDate) { 
     $(this).addClass('past'); 
     }else { 
     $(this).addClass('future'); 
     } 
    }); 
}); 
+0

甜!謝謝你,先生! – sandalkoyak

+0

歡迎您:) –