你建的方式,所有的全局命名空間,使得它非常難以將兩個定時器。相反,你應該只使用可重用的對象構造函數。 Demo here。
function Countdown(element, time) {
this.element = element;
this.time = time;
}
Countdown.time = function() {
return new Date().getTime()/1000;
};
Countdown.formatRemaining = function(timeRemaining) {
function fillZero(n) {
return n < 10 ? '0' + n : n.toString();
}
var days = timeRemaining/60/60/24 | 0;
var hours = timeRemaining/60/60 | 0;
var minutes = timeRemaining/60 | 0;
var seconds = timeRemaining | 0;
hours %= 24;
minutes %= 60;
seconds %= 60;
return days + ' day' + (days === 1 ? '' : 's') + ' ' + fillZero(hours) + ':' + fillZero(minutes) + ':' + fillZero(seconds);
};
Countdown.prototype.update = function() {
var timeRemaining = this.time + this.start - Countdown.time();
if(timeRemaining > 0) {
this.element.innerHTML = Countdown.formatRemaining(timeRemaining);
} else {
this.element.innerHTML = "Time's up!";
if(this.timer) {
clearInterval(this.timer);
this.timer = null;
}
}
};
Countdown.prototype.start = function() {
var countdown = this;
this.start = Countdown.time();
this.timer = setInterval(function() {
countdown.update();
}, 1000);
this.update();
};
它不起作用的原因是因爲jsFiddle自動將它包裝在'onload'處理程序中。 – Ryan 2012-01-08 16:48:03
這裏是jsFiddle的問題解決:http://jsfiddle.net/minitech/s7x2d/2/ – Ryan 2012-01-08 16:50:01
感謝您排序jsFiddle問題。任何想法如何實際創建2個實例 – user866190 2012-01-08 17:03:16