如果需要使用$.fn.digits
方法,请在设置.digits()
元素的.html
之后调用#steps
:
<div> <h2> Total Steps: <span id="steps" class="commas"></span></h2> </div>
<script>
var from_date = new Date("2020-01-01 00:00:00") /1000;
var now = Date.now() / 1000;
var year2020 = now - from_date;
var speed = 100;
// Random Meter
$(document).ready(function () {
go();
setInterval(function () {
go();
}, speed);
});
var random_increment = Math.floor((Math.random() * 5) + 5);
function go() {
$("#steps").html(year2020.toFixed(0));
year2020 += random_increment;
}
</script>
其输出类似:
总步骤:3943958(增加)。>>
现在,我想每3位加上逗号,然后找到一个代码
$.fn.digits = function(){ return this.each(function(){ $(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") ); }) }
所以,如何获得类似输出
总步骤数:3,943,958(每秒增加)
?
谢谢,
如果需要使用$.fn.digits
方法,请在设置.digits()
元素的.html
之后调用#steps
:
var from_date = new Date("2020-01-01 00:00:00") / 1000; var now = Date.now() / 1000; var year2020 = now - from_date; var speed = 100; var random_increment = Math.floor((Math.random() * 5) + 5); function go() { $("#steps") .html(year2020.toFixed(0)) .digits(); year2020 += random_increment; } $.fn.digits = function() { return this.each(function() { $(this).text($(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")); }) } go(); setInterval(go, speed);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <h2> Total Steps: <span id="steps" class="commas"></span></h2> </div>
但是直接在.replace
字符串上调用year2020.toFixed
会更简单:
var from_date = new Date("2020-01-01 00:00:00") / 1000; var now = Date.now() / 1000; var year2020 = now - from_date; var speed = 100; var random_increment = Math.floor((Math.random() * 5) + 5); function go() { const newStr = year2020 .toFixed() .replace(/\d(?=(?:\d{3})+(?!\d))/g, "$&,"); $("#steps").text(newStr); year2020 += random_increment; } go(); setInterval(go, speed);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <h2> Total Steps: <span id="steps" class="commas"></span></h2> </div>
注意:
#steps
元素仅包含纯文本,所以.text
比.html
更合适toFixed
的参数默认为0:不需要显式传递0。$&
替换为该数字\d\d\d
的精神,\d{3}
可以用DRY代替go
函数是您要在每个时间间隔上调用的函数,因此您只需将go
传递给setInterval
(无需将其包装在another如果需要使用$.fn.digits
方法,请在设置.digits()
元素的.html
之后调用#steps
: