2012-01-08 21 views
0

我寫了一個簡單的Javascript函數(curteousy的codecall.net),它創建了一個倒數計時器。Objectify Javascript - 如何運行多個Javascript函數

它運行良好,當我運行它,但我想在頁面上有多個計時器。

當我把函數放在另一個div裏時,我在屏幕上得到數字,但是最後一個函數只有一個實際上倒數了。

I have placed a link to the code here in JsFiddle由於某種原因或不想運行它,但它的工作原理。我只需要它的多個實例。

任何幫助非常感謝,謝謝提前

+0

它不起作用的原因是因爲jsFiddle自動將它包裝在'onload'處理程序中。 – Ryan 2012-01-08 16:48:03

+2

這裏是jsFiddle的問題解決:http://jsfiddle.net/minitech/s7x2d/2/ – Ryan 2012-01-08 16:50:01

+0

感謝您排序jsFiddle問題。任何想法如何實際創建2個實例 – user866190 2012-01-08 17:03:16

回答

1

你建的方式,所有的全局命名空間,使得它非常難以將兩個定時器。相反,你應該只使用可重用的對象構造函數。 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(); 
}; 
+0

感謝minitech,我是JavaScript新手,我可以看到你實例化對象的位置。我希望這從PHP的foreach循環運行,所以我會爲循環中的每個元素分別實例化?或者我會不會在JavaScript文件中... – user866190 2012-01-08 17:12:09

+0

@ user866190:這是一個多功能的課程,您可以像以前一樣使用它; '新倒計時(document.getElementById(elementId),timeInSeconds).start();',在你做同樣的地方。如果需要的話。但是,當您開始深入JavaScript時,您應該使用* HTML類*來完成此操作。 – Ryan 2012-01-08 17:13:58