2013-04-26 61 views
9

我想在頁面中的元素內增加一個數字。但是我需要這個數字來包含第千個地方值的逗號。 (例如45,000而不是45000)如何使用jQuery使用逗號來增加數字?

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

如何使用帶逗號的動畫來增加數字?

+0

看一看這個 http://stackoverflow.com/questions/7327046/jquery-number-formatting – 2013-04-26 02:43:31

+0

我會將數字存儲在數據屬性中,然後在元素中顯示數字的逗號格式化版本。當你增加它時,只需增加數據版本並替換格式化的版本。 – 2013-04-26 02:50:46

+0

這可能對你有幫助 - http://stackoverflow.com/questions/1990512/add-comma-to-numbers-every-three-digits-using-jquery – 2013-04-26 02:50:49

回答

38

工作演示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; 
    } 

**輸出* enter image description here

+0

任何想法爲什麼這個數字是不一樣的?我正在考慮圍繞輸出的圓圈。 – 2014-05-05 19:43:56

+0

Hiya @AdrianFlorescu嗯你是怎麼說的,抱歉不知道你在問什麼? ':''你的意思是爲什麼輸出不是說例如:44444?像這樣:http://jsfiddle.net/hVpqD/ – 2014-05-05 21:05:37

+0

@Tats_innit恰好,但看起來像這是因爲動畫步驟。我用完整的值替換了原始值。完成:function(){ where.text(endNr); } http://jsfiddle.net/5yBt8/10/ – 2014-05-06 07:41:15

10

您還應該添加一個完整的功能,例如:

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

更新小提琴:Demo

+0

爲什麼?我相當確定即使在最後一個動畫步驟中也會調用「step」函數。完成所有步驟完成後,使用'complete'函數附加回調函數。 – Bungle 2015-09-05 05:31:08

+0

有時它不會顯示出好的最後結果,它在最後是隨機的,有時是45000,有時是4995等等,所以我添加了這個功能,現在它工作得很好。謝謝! – 2015-10-13 09:22:52