所以我有这个更新段落的javascript,但它只输出NaN
。当我点击按钮之前检查var coins
它输出?
时,如果我按下HTML中的按钮,每次点击它时都会添加0.01
,然后我的输出结束像这样?0.010.010.010.01.01...
知道为什么会这样吗?
var Cpc = 0.01; //Coins per Click
var coins = 0; //Coins
var cps = 0; //Coins per Sec
setInterval(update, 10);
function update() {
var coinsFix = Number(Math.round(coins + 'e2') + 'e-2');
document.getElementById('Coins').innerHTML = coinsFix + ' $';
document.getElementById('CoinsB').innerHTML = coinsFix;
document.getElementById('Cps').innerHTML = cps + ' Cps';
}
function CPC() {
function cpc() {
var addCoins = coins + Cpc;
return addCoins;
}
coins = cpc();
}
<div class="rightBox">
<div id="ClickSpot">
<button id="clickButton" onClick="CPC()"> <img src="ClickerCoin.png" alt="ClickerSpot" class="ClickerSpot"> </button>
</div>
</div>
<div class="bottomBox">
<p id="Coins">Coins</p>
<div id="CoinsB" style="display: none"></div>
<p id="Cps">Cps</p>
</div>
答案 0 :(得分:0)
您可以使用两位数的Number.toFixed
。结果是一个字符串。
toFixed()
方法使用定点表示法格式化数字。
var coinsFix = coins.toFixed(2);
// ^^^^^^^^^^^
var Cpc = 0.01; //Coins per Click
var coins = 0; //Coins
var cps = 0; //Coins per Sec
setInterval(update, 10);
function update() {
var coinsFix = coins.toFixed(2);
document.getElementById('Coins').innerHTML = coinsFix + ' $';
document.getElementById('CoinsB').innerHTML = coinsFix;
document.getElementById('Cps').innerHTML = cps + ' Cps';
}
function CPC() {
function cpc() {
var addCoins = coins + Cpc;
return addCoins;
}
coins = cpc();
}
<div class="rightBox">
<div id="ClickSpot">
<button id="clickButton" onClick="CPC()"> <img src="ClickerCoin.png" alt="ClickerSpot" class="ClickerSpot"> </button>
</div>
</div>
<div class="bottomBox">
<p id="Coins">Coins</p>
<div id="CoinsB" style="display: none"></div>
<p id="Cps">Cps</p>
</div>
答案 1 :(得分:-1)
更改
setInterval(update, 10);
到
setInterval("update()", 10);
也
var coinsFix = Number(Math.round(coins + 'e2') + 'e-2');
到
var coinsFix = coins.toFixed(2);
试试这个:
var Cpc = 0.01; //Coins per Click
var coins = 0; //Coins
var cps = 0; //Coins per Sec
setInterval("update()", 10);
function update() {
var coinsFix = coins.toFixed(2);
document.getElementById('Coins').innerHTML = coinsFix + ' $';
document.getElementById('CoinsB').innerHTML = coinsFix;
document.getElementById('Cps').innerHTML = cps + ' Cps';
}
function CPC() {
function cpc() {
var addCoins = coins + Cpc;
return addCoins;
}
coins = cpc();
}
<div class="rightBox">
<div id="ClickSpot">
<button id="clickButton" onClick="CPC()"> <img src="ClickerCoin.png" alt="ClickerSpot" class="ClickerSpot"> </button>
</div>
</div>
<div class="bottomBox">
<p id="Coins">Coins</p>
<div id="CoinsB" style="display: none"></div>
<p id="Cps">Cps</p>enter code here
</div>