在此Jquery Countup中添加逗号

时间:2015-02-08 11:58:40

标签: javascript jquery

我正在尝试使用一个计数脚本来计算45,000,但需要帮助确保最终产品有一个逗号分隔符(45,000而不是45000)。有人可以帮忙吗?

大时间提前谢谢你!

这是我的代码:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript"><!--
jQuery(function($) {
    $('.timer').countTo({
        from: 5000,
        to: 45000,
        speed: 5000,
        refreshInterval: 50,
        onComplete: function(value) {
            console.debug(this);
        }
    });
});
//--></script>

<h3><span class="timer" style="font-size: 7em; text-align: center;"></span></h3>


<script>
(function($) {
$.fn.countTo = function(options) {
    // merge the default plugin settings with the custom options
    options = $.extend({}, $.fn.countTo.defaults, options || {});

    // how many times to update the value, and how much to increment the value on each update
    var loops = Math.ceil(options.speed / options.refreshInterval),
        increment = (options.to - options.from) / loops;

    return $(this).each(function() {
        var _this = this,
            loopCount = 0,
            value = options.from,
            interval = setInterval(updateTimer, options.refreshInterval);

        function updateTimer() {
            value += increment;
            loopCount++;
            $(_this).html(value.toFixed(options.decimals));

            if (typeof(options.onUpdate) == 'function') {
                options.onUpdate.call(_this, value);
            }

            if (loopCount >= loops) {
                clearInterval(interval);
                value = options.to;

                if (typeof(options.onComplete) == 'function') {
                    options.onComplete.call(_this, value);
                }
            }
        }
    });
};

$.fn.countTo.defaults = {
    from: 0,  // the number the element should start at
    to: 100,  // the number the element should end at
    speed: 1000,  // how long it should take to count between the target numbers
    refreshInterval: 100,  // how often the element should be updated
    decimals: 0,  // the number of decimal places to show
    onUpdate: null,  // callback method for every time the element is updated,
    onComplete: null,  // callback method for when the element finishes updating
};
})(jQuery);

1 个答案:

答案 0 :(得分:0)

希望这个功能有所帮助:

function addCommas(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

由于