用setInterval(jQuery)反编号

时间:2015-09-29 03:01:06

标签: javascript jquery html

我试图用set interval来计算数据属性中定义的数字。 我的代码在这里。

$( ".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

3 个答案:

答案 0 :(得分:2)

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

  1. 您可以使用html()text()设置值
  2. 使用一元+运算符
  3. 将从DOM重新检索的值转换为数字
  4. 更新当前元素的值。
  5. 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>
    &#13;
    &#13;
    &#13;

答案 1 :(得分:1)

您的问题在于此行$('.number').html(count);

这意味着它将number类的所有元素设置为等于count。您应该使用$(this)代替。

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

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

http://jsfiddle.net/21jqbtv9/3/

答案 2 :(得分:0)

可能这就是你想要的:

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

  $(this).html(count);

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

http://jsfiddle.net/21jqbtv9/4/