我正在使用JSFiddle中的代码在我的网站上实施计数功能。我喜欢它,因为它允许我定位特定div中显示的数字,我不需要在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 :(得分: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();