我无法从输入元素获取数值,即使使用 parseInt
I cannot obtain numerical values from input elements, even using parseInt
我正在制作一个速度计算器,您可以在其中输入数字并获得速度。
这是代码...
<html>
<head><title>speed</title></head>
<body>
<font face="arial">
<h1>Speed Calculator</h1>
<form>
distance: <input type="text" size="3" id="distance">
</form>
time: <input type="text" size="3" id="hours"> Hours
<pre>
<pre>
<input type="button" value="Speed" id="button">
<script>
var dist = parseInt(document.getElementById("distance").value, 10);
var hours = parseInt(document.getElementById("hours").value, 10);
var speed = parseInt(dist, 10) + parseInt(hours, 10);
var button = document.getElementById("button");
button.onclick = function () {
alert("the speed you were traveling is " + speed + "mph")
}
</script>
</font>
<body>
<html>
我输入数字,但它 returns "the speed you were traveling is NaNmph"。
有办法解决这个问题吗?
这将在页面加载时检索表单域的值,但它们仍然是空的。您需要在 button.onclick
函数中设置这些变量,以便它们在按下按钮时获得字段的值。
您只需 parseInt
值一次。
我正在制作一个速度计算器,您可以在其中输入数字并获得速度。 这是代码...
<html>
<head><title>speed</title></head>
<body>
<font face="arial">
<h1>Speed Calculator</h1>
<form>
distance: <input type="text" size="3" id="distance">
</form>
time: <input type="text" size="3" id="hours"> Hours
<pre>
<pre>
<input type="button" value="Speed" id="button">
<script>
var dist = parseInt(document.getElementById("distance").value, 10);
var hours = parseInt(document.getElementById("hours").value, 10);
var speed = parseInt(dist, 10) + parseInt(hours, 10);
var button = document.getElementById("button");
button.onclick = function () {
alert("the speed you were traveling is " + speed + "mph")
}
</script>
</font>
<body>
<html>
我输入数字,但它 returns "the speed you were traveling is NaNmph"。 有办法解决这个问题吗?
这将在页面加载时检索表单域的值,但它们仍然是空的。您需要在 button.onclick
函数中设置这些变量,以便它们在按下按钮时获得字段的值。
您只需 parseInt
值一次。