我有一个显示计数器的 JavaScript 函数。计时器从总值的 50% 开始,当达到 95% 时,计数器将减慢速度。这工作正常,但我需要显示具有不同值的多个计数器。这是我的jsfiddle
html
<span class="counter" data-count="100"></span><br/>
<span class="counter" data-count="200"></span><br/>
<span class="counter" data-count="300"></span><br/>
脚本
var total=$('.counter').data('count'),
count=Math.ceil(total/2),//set span to half of total by default
speed=50,
ninetyFivePercent = Math.floor(total*.95);
$('span').text(count);
//start counter after 2 seconds
setTimeout(function(){
counter=setInterval(timer, speed);
},2000);
function timer(){
count=count+1;
if (count === ninetyFivePercent+1){
console.log('at 95%');
clearInterval(counter);
speed = 1000;
counter=setInterval(timer, speed);
}else if (count === total+1){
console.log('complete');
clearInterval(counter);
return;
}
$('.counter').text(count);
}
//$('.counter').each(function(){
// var total=$(this).data('count');
// var count= Math.ceil(total/2);
// var ninetyFivePercent = Math.floor(total*.95);
// $(this).text(count);
//});
最佳答案
一种解决方案是使用
$('counter').each(function(index, element) {
// here you declare local variables and functions.
}
您几乎可以使用所有代码。唯一的区别是变量和函数必须是局部的,位于函数内部。
检查http://jsfiddle.net/3eegzfaa/2/
还有一件事:尝试使用var myVariable来声明变量。也许你可以使用 Sublime Text 3 和 jslint 插件进行在线 javascript 语法检查。它与您的问题无关,但当您在 javacript 中编码时这是一个很好的做法。
您好!
关于javascript - 如何在javascript中使用.each()来显示不同的计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30091159/