javascript - 使用 setInterval (jQuery) 计算数字

标签 javascript jquery html

我正在尝试用设置的时间间隔计算数据属性中定义的数字。 我的代码在这里。

$( ".number" ).each(function(index) {
  var INCREMENT = $(this).data('increment');
  var START_VALUE = 0;
  var count = 0;
  count = INCREMENT;

  $(this).html(count);

  window.setInterval( function(index){
  count += INCREMENT;
      $('.number').html(count);
  }, 1000);
});

我最初能够获取数字,但使用 setInterval,所有这些都使用数组中的第一个数字。

WORKING FIDDLE

最佳答案

$('.number').html(count); 将设置所有匹配元素的 innerHTML。

  1. 您可以使用html()text() 来设置值
  2. 使用一元 + 运算符将从 DOM 中获取的值转换为数字
  3. 更新当前元素的值。

Demo

function update() {
  // For each of the `.number` element
  $(".number").html(function(index, oldHTML) {
    var increment = +$(this).data('increment') || 0; // Get the increament value and convert it to number or set to 0 if none
    return +oldHTML + increment; // Update the respective element
  });
}

window.setInterval(update, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="number" data-increment="2"></div>
<div class="number" data-increment="3"></div>
<div class="number" data-increment="4"></div>

关于javascript - 使用 setInterval (jQuery) 计算数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32835001/

相关文章:

javascript - 如何解决这个onclick尴尬呢?

javascript - 使用 ngTable 或类似工具将行绑定(bind)到 URI?

jquery - 无法将高度设置为百分比

javascript - JS从对象中获取数组

javascript - 是否可以使用 jQuery.attr() 函数设置多个数据属性?

html - 无法使下拉意味着

javascript - 如何使用 Breeze 导航属性对 knockout 中的 html 表进行排序?

javascript - 用户滚动到特定div的底部时,标题应显示

转换为 Django 模板时的 Javascript 问题

javascript - 语法错误 : unexpected end of input parseJSON