使用 JavaScript 将文本框中的两个数字相加
我只是想编写一个简单的 JavaScript 程序,该程序将演示如何从文本字段获取用户输入,然后单击按钮将在段落中显示这些数字的求和结果。但不幸的是下面的代码不起作用。单击该按钮会在段落中显示 NAN。
<input type="text" name="" id="num1"><br><br>
<input type="text" name="" id="num2"><br> <br>
<button id="add">Answer</button>
<br>
<p id="para"></p>
<script>
let num1=parseInt(document.getElementById("num1"));
let num2=parseInt(document.getElementById("num2"));
let add=document.getElementById("add");
add.addEventListener("click",function(){
document.getElementById("para").innerHTML=num1+num2;
});
</script>
I was just trying to write a simple javascript program that will demonstrate to take user input from text field, and clicking the button will display the summation result of those number in a paragraph. But unfortunately the below code is not working. Clicking the button shows NAN in the Paragraph.
<input type="text" name="" id="num1"><br><br>
<input type="text" name="" id="num2"><br> <br>
<button id="add">Answer</button>
<br>
<p id="para"></p>
<script>
let num1=parseInt(document.getElementById("num1"));
let num2=parseInt(document.getElementById("num2"));
let add=document.getElementById("add");
add.addEventListener("click",function(){
document.getElementById("para").innerHTML=num1+num2;
});
</script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在获取 elementById,但未获取该 ID 值。
在 getElementById 末尾添加 .value
You are getting the elementById, but not getting that IDs value.
Add .value on the end of your getElementById
您需要获取 num1 和 num2 的值,并且需要在单击后获取该值 - 所以在您的函数内
you need to get the value of num1 and num2 and you need to get the value after you click -- so inside your function
你可以简单地这样做,
这是工作代码的演示
You can simply do it like this
here is the demo of working code