1

我正在逐步完成每一类 .days-due 以添加一个倒计时数字,直到到期日。EG:2 天内到期 - 到期日期:2/8/2013

我还希望它显示超过截止日期的负数。

http://jsfiddle.net/infatti/XeqPT/#base

到期日数错误,我不明白为什么?

<ul>
<li>Due in <span class="days-due"></span> days - Due Date is <span class="month">02</span>/<span class="day">08</span>/<span class="year">2013</span></li>
<li>Due in <span class="days-due"></span> days - Due Date is <span class="month">02</span>/<span class="day">10</span>/<span class="year">2013</span></li>
</ul>

function daysUntil(year, month, day) {
  var now = new Date(),
      dateEnd = new Date(year, month - 1, day), // months are zero-based
      days = (dateEnd - now) / 1000/60/60/24;   // convert milliseconds to days

  return Math.round(days);
}

var monthDue = $(this).next('.month').text();
var dayDue = $(this).next('.day').text();
var yearDue = $(this).next('.year').text();

$('.days-due').each(function(){
    $(this).text(daysUntil(yearDue, monthDue, dayDue));
});
4

1 回答 1

1

$(this)在您的上下文中是指window.

next看着兄弟姐妹。您的跨度不是窗口的兄弟姐妹。

更改您的选择器。此外,您的代码只查看一组元素,但您的标记有两个。

试试这个

function daysUntil(year, month, day) {
    var now = new Date(),
        dateEnd = new Date(year, month - 1, day); // months are zero-based
    days = (dateEnd - now) / 1000 / 60 / 60 / 24; // convert milliseconds to days
    return Math.round(days);
}

$("li").each(function () {

    var monthDue = $(this).find('.month').text();
    var dayDue = $(this).find('.day').text();
    var yearDue = $(this).find('.year').text();

    $(this).find(".days-due").text(daysUntil(yearDue, monthDue, dayDue));

});

找到所有li元素,然后循环遍历它们进行计算。因为我们选择了更改li的上下文。this

于 2013-02-06T20:09:34.093 回答