如何将类添加到具有最接近值的元素

时间:2014-01-10 11:09:57

标签: javascript jquery date

我正在制作带日期的活动日历,并希望在下一个即将到来的日期(最接近当前日期)添加课程

HTML

<div>
   <div class=".date" id="9,18,2013">18th Sept 2013: Going Fishing</div>
   <div class=".date" id="22,01,2014">22nd Jan 2014: Going on Holiday to Greece</div>
   <div class=".date" id="16,02,2014">16th Feb 2014: Business Meeting</div>
   <div class=".date" id="27,02,2014">27th Feb 2014: Sisters Birthday</div>
</div>

的javascript / jquery的

var today = new Date();
  var a = $(".date").attr('id')
  var b = a.split(",");
  var c = new Date(b[2], b[0], b[1]);

这会将id值更改为日期,但我需要找到与变量“today”最接近的那个

1 个答案:

答案 0 :(得分:1)

如果元素按照示例中给出的那样排序,那么

<div>
    <div class="date" id="18,9,2013">18th Sept 2013: Going Fishing</div>
    <div class="date" id="22,01,2014">22nd Jan 2014: Going on Holiday to Greece</div>
    <div class="date" id="16,02,2014">16th Feb 2014: Business Meeting</div>
    <div class="date" id="27,02,2014">27th Feb 2014: Sisters Birthday</div>
</div>

var today = new Date();
//clear the time part
today.setHours(0, 0, 0, 0);
//need to remove the . from the class attribute of the elements
$('.date').each(function () {
    var parts = this.id.split(",");
    var date = new Date(parts[2], parts[1], parts[0]);
    if (date - today > 0) {
        $(this).addClass('next');
        //return false to prevent the iteration of any other element
        return false;
    }
})

演示:Fiddle