如何调整此脚本以正确处理格式化数字并避免 NaN 错误?
$('.count').each(function() {
$(this).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 2000,
easing: 'swing',
step: function(now) {
$(this).text(Math.ceil(now));
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="count">1,745</span>
最佳答案
从计数中删除逗号,即 1,745 变为 1745。要保留逗号,请将 toLocaleString()
添加到文本中:
编辑:关于bhansa的评论,可以找到Number.prototype.toLocaleString()
的MDN文档here .
$('.count').each(function() {
$(this).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 2000,
easing: 'swing',
step: function(now) {
$(this).text(Math.ceil(now).toLocaleString());
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="count">1745</span>
关于jQuery 对格式化数字的计数效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49497640/