将逗号添加到数字的问题

时间:2016-06-02 01:57:12

标签: javascript jquery

我已为roundNum实施了一个逗号,其中显示了正在移动的总数;

    $.fn.digits = function(){ 
        return this.each(function(){ 
            $(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") ); 
        });
    };

$('.total').text(roundNum).digits();

但是我似乎无法对实际的计数器做同样的事情。

$.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
};


$('.timer').countTo({
    from: 0,
    to: roundNum,
    speed: speed,
    refreshInterval: 600,
    onComplete: function() {
        console.debug(this);
    }
});

1 个答案:

答案 0 :(得分:1)

问题在于:

<form editable-form></form>

返回一个字符串。因此,当您尝试将$('.total').text(roundNum) 添加到其末尾时:

.digits()

它正在查找字符串上的$('.total').text(roundNum).digits(); 方法,而不是jQuery对象,因为这是.digits()返回的内容。

有几种可能的方法,具体取决于您希望如何工作。可能最有意义的是将你的$('.total').text(roundNum)代码变成一个接受传入数字或字符串的普通函数并返回一个逗号字符串,这样你就可以这样做了:

digits()