如何使用jQuery使用逗号来增加数字?
我想在页面中的元素内增加一个数字。但是我需要这个数字来包含第千个地方值的逗号。 (例如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>
如何使用带逗号的动画来增加数字?
工作演示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;
}
**输出*
任何想法为什么这个数字是不一样的?我正在考虑围绕输出的圆圈。 – 2014-05-05 19:43:56
Hiya @AdrianFlorescu嗯你是怎么说的,抱歉不知道你在问什么? ':''你的意思是为什么输出不是说例如:44444?像这样:http://jsfiddle.net/hVpqD/ – 2014-05-05 21:05:37
@Tats_innit恰好,但看起来像这是因为动画步骤。我用完整的值替换了原始值。完成:function(){ where.text(endNr); } http://jsfiddle.net/5yBt8/10/ – 2014-05-06 07:41:15
您还应该添加一个完整的功能,例如:
step:function(){
//..
},
complete:function(){
$el.text(commaSeparateNumber(Math.round(this.someValue)));
}
更新小提琴:Demo
为什么?我相当确定即使在最后一个动画步骤中也会调用“step”函数。完成所有步骤完成后,使用'complete'函数附加回调函数。 – Bungle 2015-09-05 05:31:08
有时它不会显示出好的最后结果,它在最后是随机的,有时是45000,有时是4995等等,所以我添加了这个功能,现在它工作得很好。谢谢! – 2015-10-13 09:22:52
看一看这个 http://*.com/questions/7327046/jquery-number-formatting – 2013-04-26 02:43:31
我会将数字存储在数据属性中,然后在元素中显示数字的逗号格式化版本。当你增加它时,只需增加数据版本并替换格式化的版本。 – 2013-04-26 02:50:46
这可能对你有帮助 - http://*.com/questions/1990512/add-comma-to-numbers-every-three-digits-using-jquery – 2013-04-26 02:50:49