2014-02-11 73 views
0

我使用的代碼來自JSFiddle在我的網站上實現向上計數功能。我喜歡它,因爲它允許我定位顯示在特定div中的數字,而且我不需要在JavaScript中指定該數字,這意味着我可以在任何頁面上爲我選擇的任何數字使用它。停止JavaScript計數器,一旦達到指定的格數

在這裏看到的代碼:

// basic class implementation 
function myCounter() { 
    // privileged property for iteration 
    this.i = 0; 

    // privileged init method 
    this.init(); 
} 

// defining init method 
myCounter.prototype.init = function() { 
    // reassign this 
    var _this = this; 

    setInterval(function() { 
     // call this.countUp() using our new created variable. 
     // this has to be done as this would normally call something 
     // inside this function, so we have to pass it as own 
     // variable over 
     _this.countUp(); 
    }, 500); 

    clearInterval(function() { 
     this.i == 
    }; 
}; 

// defining the counter method 
myCounter.prototype.countUp = function() { 
    this.i++; 
    document.getElementById('counter').innerHTML = this.i; 
}; 

// create a new instance of our counter class 
var counter = new myCounter(); 

唯一的問題是,它不會停止計數。我很想爲自己添加一些代碼,除了我對JavaScript不夠熟悉並且不知道從哪裏開始。

有沒有辦法讓javascript停止計數在目標div中指定的數量?

非常感謝!

+0

我會建議做一個if語句if(this.i ==任何你想要的) – KRUKUSA

回答

0
// basic class implementation 
function myCounter() { 
    // privileged property for iteration 
    this.i = 0; 

    // privileged init method 
    this.init(); 
} 

// defining init method 
myCounter.prototype.init = function() { 
    // reassign this 
    var _this = this; 
    this.timer = setInterval(function() { 
     // call this.countUp() using our new created variable. 
     // this has to be done as this would normally call something 
     // inside this function, so we have to pass it as own 
     // variable over 
     _this.countUp(); 
    }, 500); 
}; 

// defining the counter method 
myCounter.prototype.countUp = function() { 
    this.i++; 
    document.getElementById('counter').innerHTML = this.i; 

    // stop the timer 
    if(this.i == 8){ 
     clearInterval(this.timer) 
    } 
}; 

// create a new instance of our counter class 
var counter = new myCounter(); 
+0

非常感謝!這很好,但是可以停止計數在HTML(使用id)中指定的數量,而不是在JS? – hmakein

+0

其實,我剛剛意識到我以前的請求不可能(我認爲),因爲在javascript開始時#counter的值被設置爲0。因此,我通過將我想要計算的數字放入數據屬性中,然後創建了一個變量,從而使您的代碼正常工作: var countLimit = count.getAttribute('data-attribute'); 並使用clearInterval。謝謝! – hmakein

相關問題