10

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)

<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?

4

2 回答 2

44

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

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

代码

// 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, "$1,");
    }
    return val;
  }

**输出* 在此处输入图像描述

于 2013-04-26T03:10:29.450 回答
11

您还应该像这样添加一个完整的功能:

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

更新的小提琴:演示

于 2014-07-18T08:11:32.360 回答