一旦javascript计数器达到div中指定的数字,就停止它
我正在使用来自的代码在我的站点上实现一个计数功能。我喜欢它,因为它允许我以特定div中显示的数字为目标,而我不需要在javascript中指定该数字,这意味着我可以在任何页面上为我选择的任何数字使用它 请参见此处的代码:一旦javascript计数器达到div中指定的数字,就停止它,javascript,counter,Javascript,Counter,我正在使用来自的代码在我的站点上实现一个计数功能。我喜欢它,因为它允许我以特定div中显示的数字为目标,而我不需要在javascript中指定该数字,这意味着我可以在任何页面上为我选择的任何数字使用它 请参见此处的代码: // basic class implementation function myCounter() { // privileged property for iteration this.i = 0; // privileged init metho
// 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中指定的数字计数
非常感谢 我建议做一个if语句if(this.I==无论你想要什么)非常感谢!这很好,但是可以在HTML中指定的数字(使用id)而不是JS中停止计数吗?事实上,我刚刚意识到我之前的请求不可能(我认为),因为在javascript开始时#counter的值被设置为0。因此,我通过将我想要计数的数字放入数据属性中,使代码正常工作,然后我创建了一个变量:var countLimit=count.getAttribute('data-attribute');并在上面使用了clearInterval。非常感谢。
// 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();