即使使用 parseInt,我也无法从输入元素中获取数值

I cannot obtain numerical values from input elements, even using parseInt

本文关键字:输入 元素 获取 取数值 parseInt      更新时间:2023-09-26

我正在制作一个速度计算器,您可以在其中输入数字并获得速度。这是代码...

<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>

我输入数字,但它返回"您行驶的速度是 NaNmph"。有没有办法解决这个问题?

这将在加载页面时检索表单字段的值,并且它们仍然为空。 您需要改为在 button.onclick 函数中设置这些变量,以便它们获取截至按下按钮时的字段值。

您只需parseInt一次值。