如果有多个元素初始化,我有一个问题是更新计数器容器时间倒计时。在这种情况下,最后一个容器正在更新,并且倒计时秒被包含
插件代码
(function( $ ){
var methods = {
container: null,
init : function(options) {
var timestamp = $(this).data('release'), id = $(this).attr('id');
if (!timestamp) return;
methods.container = $('#' +id);
console.log(methods.container)
methods.times = {days: 0, hours: 0, minutes: 0, seconds: 0};
time = new Date();
methods.secondsToGo = timestamp - Math.round(time/1000) + (time.getTimezoneOffset() * 60);
methods.calcTimes();
},
calcTimes: function() {
secondsToGo = methods.secondsToGo;
// Countdown end is in the past
if (secondsToGo < 0) return;
methods.container.show();
// Calculate times
methods.times.days = Math.floor(secondsToGo/86400);
if (this.times.days > 99) this.times.days = 99; // max. 2 digits
secondsToGo = secondsToGo%86400;
methods.times.hours = Math.floor(secondsToGo/3600);
secondsToGo = secondsToGo%3600;
methods.times.minutes = Math.floor(secondsToGo/60);
methods.times.seconds = secondsToGo%60;
methods.updateCounter();
// Minus 1 second
methods.secondsToGo--;
// Loop
setTimeout(function(){
methods.calcTimes();
}.bind(this), 1000);
},
updateCounter: function() {
for(var prop in this.times) {
pre = '';
if (this.times[prop] < 10) pre = '0'; // min. 2 digits
// number to string
this.times[prop] = pre + this.times[prop];
times = this.times; // ... because I can't use this.times in each-loop
dnb = 0;
methods.container.find('.number-block-' + prop).children('.number').each(function(){
$(this).html(times[prop][dnb]);
dnb++;
})
}
}
};
$.fn.countdown = function(methodOrOptions) {
if ( methods[methodOrOptions] ) {
return methods[ methodOrOptions ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) {
// Default to "init"
$obj = this
return this.each(function() {
//$(this).append(' - ' + $(this).data('x'));
methods.init.apply( this, arguments );
});
//return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + methodOrOptions + ' does not exist on jQuery.countdown' );
}
};
})( jQuery );
问题演示codepen
问题是插件循环内部的自我更新,以及容器上的更新如何影响最后一次加载。在每一秒更新所有容器会有什么明智的解决方法?