[英]Problems Adding Commas To Numbers
我為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);
}
});
問題是:
$('.total').text(roundNum)
返回一個字符串。 因此,當您嘗試在其末尾添加.digits()
時:
$('.total').text(roundNum).digits();
它在字符串上而不是在jQuery對象上尋找.digits()
方法,因為這是$('.total').text(roundNum)
返回的結果。
有多種可行的方法,具體取決於您希望它如何工作。 也許最有意義的就是將您的digits()
代碼變成一個普通函數,該函數接受輸入的數字或字符串並返回一個逗號字符串,因此您可以執行以下操作:
$('.total').text(digits(roundNum));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.