修改countup jquery函数以包含逗号?

时间:2018-04-17 12:03:16

标签: jquery

如何修改以下内容以在输出中包含逗号?例如,300000的输出将打印为“300,000”?

html

<span class="number counter" data-count="300000">300,000</span>

魔术:

jQuery(document).ready(function($) {
    $('.counter').each(function() {
        var $this = $(this),
            countTo = $this.attr('data-count');


        $({countNum: $this.text()}).animate({
                countNum: countTo
            },
            {
                duration: 999,
                easing:'linear',
                step: function() {
                    $this.text(Math.floor(this.countNum));
                },
                complete: function() {
                    $this.text(addCommas(this.countNum));
                    console.log('finished')
                }
            });

        function addCommas(nStr){
            //return comma
        }
    });
});

这与 - How do I format numbers using JavaScript?不同 - 因为我需要使用逗号计算和显示计数器 - step期间的操作需要添加动态逗号。

1 个答案:

答案 0 :(得分:0)

您可以使用正则表达式:

nStr.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");

&#13;
&#13;
jQuery(document).ready(function($) {
    $('.counter').each(function() {
        var $this = $(this),
            countTo = $this.attr('data-count');


        $({countNum: $this.text()}).animate({
                countNum: countTo
            },
            {
                duration: 999,
                easing:'linear',
                step: function() {
                    $this.text(addCommas(Math.floor(this.countNum)));
                },
                complete: function() {
                    $this.text(addCommas(this.countNum));
                    console.log('finished')
                }
            });

        function addCommas(nStr){
            return nStr.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
        }
    });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="number counter" data-count="300000">300,000</span>
&#13;
&#13;
&#13;