jQuery 如何使用jQuery使用带有逗号的动画来增加数字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16227858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:44:27  来源:igfitidea点击:

How to increment number using animate with comma using jQuery?

jqueryjquery-animateincrementcommaeasing

提问by kevllar

I'm trying to increment a number inside an element on page. But I need the number to include a comma for the thousandth place value. (e.g. 45,000 not 45000)

我正在尝试在页面上的元素内增加一个数字。但是我需要在数字中包含一个逗号作为千位值。(例如 45,000 不是 45000)

<script>
// Animate the element's value from x to y:
  $({someValue: 40000}).animate({someValue: 45000}, {
      duration: 3000,
      easing:'swing', // can be anything
      step: function() { // called on every step
          // Update the element's text with rounded-up value:
          $('#el').text(Math.round(this.someValue));
      }
  });
</script>
<div id="el"></div>

How can I increment a number using animate with comma?

如何使用带逗号的动画来增加数字?

回答by Tats_innit

Working Demohttp://jsfiddle.net/4v2wK/

工作演示http://jsfiddle.net/4v2wK/

Feel free to change it more for your need, you can also look at the currency formatter, Hope this will fit your need :)

随意根据您的需要更改它,您也可以查看货币格式化程序,希望这能满足您的需要 :)

Code

代码

// Animate the element's value from x to y:
  var $el = $("#el"); //[make sure this is a unique variable name]
  $({someValue: 40000}).animate({someValue: 45000}, {
      duration: 3000,
      easing:'swing', // can be anything
      step: function() { // called on every step
          // Update the element's text with rounded-up value:
          $el.text(commaSeparateNumber(Math.round(this.someValue)));
      }
  });

 function commaSeparateNumber(val){
    while (/(\d+)(\d{3})/.test(val.toString())){
      val = val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, ",");
    }
    return val;
  }

**output* enter image description here

**输出* 在此处输入图片说明

回答by SuperNOVA

You should also add a complete function as such:

您还应该添加一个完整的函数:

step:function(){
    //..
},
complete:function(){
    $el.text(commaSeparateNumber(Math.round(this.someValue)));
}

Updated Fiddle: Demo

更新的小提琴:演示