使用span类格式化网页上所有数字的最佳方法是什么?使用jQuery吗?
<span class="number">100065</span>
<span class="number">9896</span>
<span class="number">3946</span>
<span class="number">9606</span>
结果 100k 9.8k 3.9k 9.6k
答案 0 :(得分:1)
有点重复,但这是您特殊情况的正确解决方案:
String.prototype.endsWith = function(suf) {
return (this.indexOf(suf, this.length - suf.length) !== -1) ? this.slice(0, -2) : this;
};
function kF(num) {
return num > 999 ?
(num/1000).toString().slice(0, - 2).endsWith('.0') + 'k' :
num
}
jQuery('span.number').text(function(i, oldText) { return kF(oldText); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="number">100065</span>
<span class="number">9896</span>
<span class="number">3946</span>
<span class="number">9606</span>
<p>Some more...</p>
<span class="number">100065568</span>
<span class="number">20054065568</span>
最新版本现在还通过 100.0k 解决了该问题。