如何在这个计数器脚本的1000中为一个数字添加一个逗号

时间:2017-02-24 20:13:54

标签: javascript jquery number-formatting

所以这个脚本计算到我添加到span的数字,但是我想在11,000之后添加一个逗号。

如果尝试添加toFixed,但它没有帮助: $(this).text(Math.ceil(now).toFixed(3));

$('.counter').each(function() {
  $(this).prop('Counter', 0).animate({
    Counter: $(this).text()
  }, {
    duration: 7000,
    easing: 'swing',
    step: function(now) {
      $(this).text(Math.ceil(now));
      stop();
      $(this).removeClass('counter');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  <div class="number">
    <span class="count counter">100</span>
  </div>
  <div class="number">
    <span class="count counter">11000</span>
  </div>

2 个答案:

答案 0 :(得分:4)

您可以使用toLocalString()

&#13;
&#13;
$('.counter').each(function() {
  $(this).prop('Counter', 0).animate({
    Counter: $(this).text()
  }, {
    duration: 7000,
    easing: 'swing',
    step: function(now) {
      $(this).text(Math.ceil(now).toLocaleString());
      // Here --------------------^
      stop();
      $(this).removeClass('counter');
    }
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  <div class="number">
    <span class="count counter">100</span>
  </div>
  <div class="number">
    <span class="count counter">11000</span>
  </div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用此功能:

$.fn.digits = function(){ 
    return this.each(function(){ 
        $(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") ); 
    })
}

然后:

$(".count counter").digits();

您也可以使用这个简单的代码来执行相同的操作:

$(this).text(now.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"));