如果某个日期距离当前日期2周或更短,我正在尝试向div添加一个类。我的逻辑是这样的,但它似乎不起作用。有任何想法吗?它似乎没有正确地进行比较(它将类添加到所有div)并且我无法弄明白。谢谢你的帮助
function dateString () {
var currentDate = new Date ();
var twoWeeks = new Date ();
twoWeeks.setDate(currentDate.getDate() + 14)
var EndDateDiv = $('.end-date');
if (currentDate <= twoWeeks) {
EndDateDiv.addClass('red');
}
};
答案 0 :(得分:1)
我愿意:
function dateString () {
var currentDate = new Date();
var twoWeeks = new Date();
twoWeeks.setDate(twoWeeks.getDate() + 14);
var limit = 15;
var EndDateDiv = $('.end-date');
var diff = Math.round((twoWeeks-currentDate)/(1000*60*60*24))
if (diff > limit) {
EndDateDiv.addClass('red');
}
};
工作小提琴==&gt; https://jsfiddle.net/r1v34aty/
答案 1 :(得分:1)
它按预期工作。请参阅以下代码段。
dateString();
function dateString () {
var currentDate = new Date ();
var twoWeeks = new Date ();
twoWeeks.setDate(currentDate.getDate() + 14)
var EndDateDiv = $('.end-date');
if (currentDate <= twoWeeks) {
EndDateDiv.addClass('red');
console.log($('.end-date').attr('class'));
}
};
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="end-date" />
&#13;
答案 2 :(得分:1)
function dateString () {
var currentDate = new Date ();
var twoWeeks = new Date ();
alert(twoWeeks);
var EndDateDiv = $('.end-date');
if (currentDate.getTime() <= twoWeeks.getTime()+(14*24*60*60)) {
EndDateDiv.addClass('red');
console.log($('.end-date').attr('class')); }
};