$<span id="money">0</span>
我有这个显示多少钱的范围。这个号码不断更新,因为这是我正在制作的空闲游戏。
function moneyClick(number) {
money = money + number;
document.getElementById("money").innerHTML = money;
lifetimeearnings = lifetimeearnings + number;
document.getElementById("lifetimeearnings").innerHTML = lifetimeearnings;
};
window.setInterval(function() {
moneyClick(thugs);
moneyClick(assassins * 3);
moneyClick(farms * 5);
moneyClick(lawyers * 11);
moneyClick(rackets * 23);
document.getElementById('thugEarn').innerHTML = thugEarn;
document.getElementById('thugs').innerHTML = thugs;
document.getElementById('assassinEarn').innerHTML = assassinEarn;
document.getElementById('assassins').innerHTML = assassins;
document.getElementById('farmEarn').innerHTML = farmEarn;
document.getElementById('farms').innerHTML = farms;
document.getElementById('lawyerEarn').innerHTML = lawyerEarn;
document.getElementById('lawyers').innerHTML = lawyers;
document.getElementById('racketEarn').innerHTML = racketEarn;
document.getElementById('rackets').innerHTML = rackets;
}, 1000);
跨度由javascript中的上述两个函数更新。我想格式化跨度以用逗号显示钱,例如1234将变为1,234和1234567将变为1,234,567。
我已经看到有办法做到这一点,但是当跨度不断更新时,它们都没有工作。有没有办法在不断更新文本时保持文本格式化?
答案 0 :(得分:0)
在将数字添加到DOM之前,只需添加逗号即可。
//A function to add commas to the number
var formatNumber = function (number) {
var splitNum;
number = Math.abs(number);
number = number.toFixed(2);
splitNum = number.split('.');
splitNum[0] = splitNum[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return splitNum.join(".");
}
function moneyClick(number) {
money = money + number;
//Add commas to the number before update the DOM
document.getElementById("money").innerHTML = formatNumber(money);
lifetimeearnings = lifetimeearnings + number;
document.getElementById("lifetimeearnings").innerHTML = lifetimeearnings;
};
window.setInterval(function() {
moneyClick(thugs);
moneyClick(assassins * 3);
moneyClick(farms * 5);
moneyClick(lawyers * 11);
moneyClick(rackets * 23);
document.getElementById('thugEarn').innerHTML = thugEarn;
document.getElementById('thugs').innerHTML = thugs;
document.getElementById('assassinEarn').innerHTML = assassinEarn;
document.getElementById('assassins').innerHTML = assassins;
document.getElementById('farmEarn').innerHTML = farmEarn;
document.getElementById('farms').innerHTML = farms;
document.getElementById('lawyerEarn').innerHTML = lawyerEarn;
document.getElementById('lawyers').innerHTML = lawyers;
document.getElementById('racketEarn').innerHTML = racketEarn;
document.getElementById('rackets').innerHTML = rackets;
}, 1000);
答案 1 :(得分:0)
您可以通过以下方式为数字添加逗号:
var number = 1234567;
document.querySelector('#money').innerHTML = number.toLocaleString();
$<span id="money"></span>
修改
另外,为确保将数字四舍五入到正确的小数位数,您可以执行以下操作:
var number = 1234.5678;
document.querySelector('#money').innerHTML = (+number.toFixed(2)).toLocaleString();
$<span id="money"></span>
在这种情况下,+符号将舍入值返回到一个数字,然后添加逗号。