我正在尝试编写这个非常简单的javascript应用程序,用户可以输入两个数字,这两个数字的总和会自动输出到屏幕。我对javascript很新,所以我不确定我哪里出错了。按下按钮后,以下代码将打印NaN一秒钟。有关如何更好地处理此输入的想法吗?
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
var x = parseInt(first_num);
var y = parseInt(second_num);
var z = x + y;
var a = z.toString();
document.getElementById("demo").innerHTML = a;
}
</script>
</head>
<body>
<p>Enter two numbers to be added together.</p>
<form>
<input id="first_num" name="first_num" > first num<br>
<input id="second_num" name="second_num" > second num
<button onclick="myFunction()">calculate</button>
<p id="demo"></p>
</body>
</html>
答案 0 :(得分:2)
var x = parseInt(first_num);
var y = parseInt(second_num);
而不是first_num
和second_num
,您需要从输入框中检索值,例如
var x = parseInt(document.getElementById("first_num").value);
var y = parseInt(document.getElementById("second_num").value);
答案 1 :(得分:2)
您必须使用选择器来获取两个input
元素的值:
var x = parseInt(document.getElementById('first_num').value);
var y = parseInt(document.getElementById('second_num').value);
...
您必须在HTML使用中关闭form
标记并使用<input type="button">
代替<button>
,这样您的表单就不会发布不必要的内容。
<form>
<input id="first_num" name="first_num" > first num <br />
<input id="second_num" name="second_num" > second num <br />
<input type="button" onclick="myFunction()" value="calculate">
</form>
答案 2 :(得分:1)
NaN的原因是你试图使用未初始化的变量来解析。此输入标记旁边没有关闭。
function myFunction() {
document.getElementById("demo").innerHTML = parseInt(document.getElementById('first_num').value) + parseInt(document.getElementById('second_num').value);
}
和html:
<p>Enter two numbers to be added together.</p>
<input id="first_num" name="first_num" />first num
<br>
<input id="second_num" name="second_num" />second num
<button onclick="myFunction()">calculate</button>
<p id="demo"></p>
答案 3 :(得分:0)
以下是一份工作样本:
<!DOCTYPE html>
<html>
<head>
<title>Page</title>
</head>
<body>
<p>Enter two numbers to be added together.</p>
<input id="first_num" name="first_num">first num<br />
<input id="second_num" name="second_num">second num<br />
<button onclick="myFunction()">calculate</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("first_num").value;
var y = document.getElementById("second_num").value;
var z = ((x && x != "") ? parseInt(x) : 0) + ((y && y != "") ? parseInt(y) : 0);
document.getElementById("demo").innerHTML = z;
}
</script>
</body>
</html>
答案 4 :(得分:0)
执行以下操作:
<p>Enter two numbers to be added together.</p>
<form>
<input id="first_num" name="first_num" > first num<br>
<input id="second_num" name="second_num" > second num
<button onclick="myFunction(parseInt(document.getElementById("first_num").value),parseInt(document. getElementById("second_num").value))">calculate</button>
<p id="demo"></p>
function myFunction(first_num,second_num)
{
var x = parseInt(first_num);
var y = parseInt(second_num);
var z = x + y;
var a = z.toString();
document.getElementById("demo").innerHTML = a;
}