简体   繁体   English

JQuery / JQuery Mobile中的格式编号

[英]Formatting Number in JQuery/JQuery Mobile

I am creating an app with Phonegap and JQuery Mobile and have a particular scenario where I need to format a particular counter. 我正在使用Phonegap和JQuery Mobile创建一个应用程序,并且有一种特殊的情况,我需要格式化特定的计数器。

Basically the counter starts from 1 and keeps increasing when a certain event is triggered. 基本上,计数器从1开始,并在触发特定事件时保持递增。 However, in order to display it i need to display them as 0001 then once an event is triggered it goes to 0002 .... 0099... 0999... 9999 (max). 但是,为了显示它,我需要将它们显示为0001,然后一旦触发事件,它将转到0002 .... 0099 ... 0999 ... 9999(最大值)。

So far what I have is outputting the number such as 15, but I cannot find how to put the 00 padding in front so that the value is always displayed as 4 characters. 到目前为止,我正在输出的数字是15,但是我找不到如何将00填充放在前面,因此该值始终显示为4个字符。

Can someone help me or direct me to any plugin available? 有人可以帮助我或将我定向到任何可用的插件吗?

Thanks! 谢谢!

To format your number, you could do 要格式化您的电话号码,您可以

var formattedNumber = ("000"+number).slice(-4);

EDIT following comment : 编辑以下评论:

You can do this : 你可以这样做 :

 var eventCounter = parseInt($('.eventCount').text(), 10) +1;
 $('.eventCount').text(("000"+number).slice(-4));  

Don't forget the second argument to parseInt , the radix, as parseInt("0009") is 0 ... 不要忘记parseInt的第二个参数,即基数,因为parseInt("0009")0 ...

But I'd suggest to use an id and not a class as selector : this would be faster as you have only one div. 但是我建议使用id而不是类作为选择器:这样会更快,因为您只有一个div。 So your HTML would be 所以你的HTML将是

<div id=eventCount>0001</div>

And your jQuery selector would be "#eventCount" instead of ".eventCount". 而且您的jQuery选择器将是"#eventCount"而不是“ .eventCount”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM