奇怪的JavaScript递增行为

时间:2015-07-09 06:52:06

标签: javascript increment

当我点击垃圾点按钮时,它有时会改变小数位数。为什么呢?

<!doctype html>
<html>

<head>

</head>

<body>

<button onmouseover="showSomething()" onmouseout="hideSomething()" onclick="addSomething()">Show something</button>
<p id="show"></p>

<script>

function showSomething() {
	x = Math.random()*100;
	x = x.toFixed(2);
	document.getElementById("show").innerHTML = x;
}

function hideSomething() {
	document.getElementById("show").innerHTML = "";
}

function addSomething() {
	x++;
	document.getElementById("show").innerHTML = x;
}

</script>

</body>

</html>

1 个答案:

答案 0 :(得分:0)

应该修复你的错误。

function addSomething() {
    x++;
    x = x.toFixed(2);
    document.getElementById("show").innerHTML = x;
}