【问题标题】:jQuery counter insert commas to break up stringjQuery 计数器插入逗号来分解字符串
【发布时间】:2015-06-16 15:15:11
【问题描述】:

我有一个每 x 秒递增一次的计数器,这是我的代码:

var counter=22000000000;
if(typeof(localStorage.getItem('counts'))!='object') {
   counter=parseInt(localStorage.getItem('counts'));
}
$(".count").html(counter);
setInterval(function () {
    $(".count").html(counter);
    ++counter;
    localStorage.setItem('counts',counter);
}, 18000);

因为起始数字太高了,看不太清楚,看这里:http://jsfiddle.net/vpju4cpr/1/

最好不要输出22000000000,我希望它阅读22,000,000,000

我该怎么做?

【问题讨论】:

标签: javascript jquery string counter


【解决方案1】:

在您的 .html() 函数中,将 counter 更改为 counter.toLocaleString() 像这样:

var counter=22000000000;
	if(typeof(localStorage.getItem('counts'))!='object') {
	   counter=parseInt(localStorage.getItem('counts'));
	}
	$(".count").html(counter.toLocaleString());
	setInterval(function () {
	    $(".count").html(counter.toLocaleString());
	    ++counter;
	    localStorage.setItem('counts',counter);
	}, 18000);

【讨论】:

    【解决方案2】:

    要用逗号格式化数字,你可以使用这个正则表达式:

    var counterString = counter.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    $(".count").html(counterString );
    

    输入:199999999

    输出:“199,999,999”

    【讨论】:

      猜你喜欢
      • 2010-10-17
      • 1970-01-01
      • 1970-01-01
      • 2021-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-26
      • 1970-01-01
      相关资源
      最近更新 更多