javascript - 如何在javascript中使用.each()来显示不同的计数器

标签 javascript jquery

我有一个显示计数器的 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/

相关文章:

javascript - HTML - Fancybox - 在图像缩略图下方添加文本

javascript - 如何测试 REST API + 客户端 MVC 应用程序?

javascript - 具有不同域 src : how to disable the click but keep the hover intact 的 HTML iframe

jquery - 使用 css 和 jquery 的信息表格导航

javascript - 在javascript中连接?

javascript - 从第三方库导入 javascript 模块

javascript - 确定路径是否是 Node.js 中另一个路径的子目录

javascript - 如何始终远离视口(viewport)传单折线?

javascript - 使用 jQuery AJAX 请求 - POST 到 php

jquery - 从日期字段(mm/dd/yyyy)中减去天数,不包括周末jquery