-2

Its been a few months since I graduated from a tech school (HS level) for programming, and my JavaScript is a bit rusty. I'm just trying to calculate Y%X=Z with textbox inputs. However Z always results in NaN, so I'm assuming my problem is the parsing.

<html>
<body>
<b>Y: </b><input type="text" id="numY" /><br>
<b>X: </b><input type="text" id="numX" /><br>
<h2>Y % X = Z</h2>
<button onclick="myFunction()">Calculate</button>
<h3><p id="demo"></p></h3>
<script>
function myFunction()
{
var y=document.getElementById('numY');
var x=document.getElementById('numX');
var z=parseInt(y)%parseInt(x);
var demoP=document.getElementById("demo")
demoP.innerHTML="z=" + z;
}
</script>

</body>
</html>
4

1 回答 1

2

xy引用<input>元素,而不是它们的值:

var y = document.getElementById('numY').value;

此外,将 radix/base 参数传递给parseInt. 您希望明确说明您使用的是 10 进制:

var z = parseInt(y, 10) % parseInt(x, 10);
于 2013-08-11T14:45:51.717 回答