向jQuery计数器添加千位分隔符

use*_*202 0 javascript formatting jquery

我正在尝试为使用跟随计数器功能的大数字添加逗号(千位分隔符):

<script type='text/javascript'>
    $(window).load(function() {
        $('.Count').each(function() {
            var $this = $(this);
            jQuery({Counter: 0}).animate({Counter: $this.text()}, {
                duration: 1500,
                easing: 'swing',
                step: function() {
                    $this.text(Math.ceil(this.Counter));
                }
            });
        });
    });
Run Code Online (Sandbox Code Playgroud)

是否要修改此特定公式,还是必须编写一个可以处理格式的附加函数?

小智 5

我遇到了同样的问题,即大量不一致的结尾(即550,000有时只算到549,826左右)。

这是一个简化的解决方案,其中toLocaleString函数可以相应地添加小数:

$('.js-count').each(function() {
   
   $(this).prop('Counter', 0).animate({
      
      Counter: $(this).data('number')
   }, {
      
      duration: 4000,
      easing: 'swing',
      step: function(now) {
         
         $(this).text(Math.ceil(now).toLocaleString('en'));
      }
   });
  
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="js-count" data-number="550000"></span>
Run Code Online (Sandbox Code Playgroud)

我还选择使用data属性存储数字。这种方式有点防弹。如果事件触发多次,则依赖元素的内容可能导致计算错误。