如果日期是今天,则添加课程 [英] add class if date is today

查看:60
本文介绍了如果日期是今天,则添加课程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些方框,它们代表出现日历中的正方形.我已经定义了data属性中每个框的日期,用于与当前日期进行比较.我正在尝试将今天"类添加到代表当天的框中.我创建了一个小提琴来演示这一点.如何解决该问题,以便将今天的课程添加到适当的框中?

I have some boxes that represent the squares in an advent calendar. I've defined the date for each box in the data attribute which I'm using to compare against the current day. I'm trying to add a class 'today' to the box that represents the current day. I've created a fiddle to demonstrate this. How can I fix it so that today class is added to the appropriate box?

JSFiddle

$(function() {
var currentDate = Date.now();

$(".grid-item").each(function() {
    var specifiedDate = $(this).data('date');
    var date = Date.parse(specifiedDate);

    if (!isNaN(date) == currentDate) {
        $(this).addClass('today');
    }
    else if(!isNaN(date) && currentDate - date > 0) {
        $(this).addClass('past');
    }
    else {
        $(this).addClass('future');
    }
});
});

推荐答案

您不必使用Date.now(),因为它不会输出与data属性相似的日期.相反,您必须像这样创建当前日期,并检查以下条件:

You don't have to use Date.now() as this doesn't outputs the dates similar to the data attributes have. Instead you have to create current date as this and check in the conditions like:

$(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');
    }
  });
});

.grid-item {
  height: 170px;
  width: 170px;
  float: left;
  background: red;
  margin: 10px;
}
.today {
  background: yellow;
  border: red 1px solid;
}
.past {
  background: black;
  border: red 1px solid;
}
.future {
  background: blue;
  border: red 1px solid;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="grid-item" data-date="2015-11-23">
</div>
<div class="grid-item" data-date="2015-11-24">
</div>
<div class="grid-item" data-date="2015-11-25">
</div>
<div class="grid-item" data-date="2015-11-26">
</div>
<div class="grid-item" data-date="2015-11-27">
</div>
<div class="grid-item" data-date="2015-11-28">
</div>
<div class="grid-item" data-date="2015-11-29">
</div>

这篇关于如果日期是今天,则添加课程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆