使用The Final Countdown jQuery计时器时,可以根据它们提供的示例之一轻松制作时区感知计时器。但现在我想在一个页面上使用多个实例而不知道如何。他们为使用多个实例提供的代码是:
HTML:
<div data-countdown="2016/01/01"></div>
<div data-countdown="2017/01/01"></div>
<div data-countdown="2018/01/01"></div>
<div data-countdown="2019/01/01"></div>
JS:
$('[data-countdown]').each(function() {
var $this = $(this), finalDate = $(this).data('countdown');
$this.countdown(finalDate, function(event) {
$this.html(event.strftime('%D days %H:%M:%S'));
});
});
看起来并不难,但在尝试将其实现到我的代码中时,它就无法正常工作。正如您在我的代码中看到的那样,它也使用不同的格式来显示时间。任何人都可以通过解释向我展示正确的方法吗?这是我的代码:
$(window).on('load', function () { "use strict";
var labels = ['weeks', 'days', 'hours', 'minutes', 'seconds'],
nextYear = moment.tz("2017-05-03 17:00", "America/Los_Angeles"),
template = _.template($('#main-countdown-template').html()),
currDate = '00:00:00:00:00',
nextDate = '00:00:00:00:00',
parser = /([0-9]{2})/gi,
$countdown = $('#main-countdown');
function strfobj(str) {
var parsed = str.match(parser),
obj = {};
labels.forEach(function (label, i) {
obj[label] = parsed[i];
});
return obj;
}
function diff(obj1, obj2) {
var diff = [];
labels.forEach(function (key) {
if (obj1[key] !== obj2[key]) {
diff.push(key);
}
});
return diff;
}
var initData = strfobj(currDate);
labels.forEach(function (label, i) {
$countdown.append(template({
curr: initData[label],
next: initData[label],
label: label
}));
});
$countdown.countdown(nextYear.toDate(), function (event) {
var newDate = event.strftime('%w:%d:%H:%M:%S'),
data;
if (newDate !== nextDate) {
currDate = nextDate;
nextDate = newDate;
data = {
'curr': strfobj(currDate),
'next': strfobj(nextDate)
};
diff(data.curr, data.next).forEach(function (label) {
var selector = '.%s'.replace(/%s/, label),
$node = $countdown.find(selector);
$node.removeClass('flip');
$node.find('.curr').text(data.curr[label]);
$node.find('.next').text(data.next[label]);
_.delay(function ($node) {
$node.addClass('flip');
}, 50, $node);
});
}
});
});