javascript错误[object HTMLInputElement] [object HTMLInputElement] [英] javascript error [object HTMLInputElement][object HTMLInputElement]

查看:123
本文介绍了javascript错误[object HTMLInputElement] [object HTMLInputElement]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在练习Java脚本代码,但是在实现此代码时遇到了问题.

i am practicing java script code but having issue while implementing this code.

<html>
<body>
<script>  
function f2(){
var a=document.getElementById("a");
var b=document.getElementById("b");
var c=a+b;
document.write(c);
}
</script>  

Enter A:<input id="a" type="text" name="txt1" ><br>
Enter B:<input id="b" type="text" name="txt2" ><br>
<button type="button" onclick="f2()">Sum Here</button>
</body>
</html>

当我将两个数字相加时,它会显示错误,例如[object HTMLInputElement] [object HTMLInputElement].

When I add two numbers then it shows error like [object HTMLInputElement][object HTMLInputElement].

推荐答案

输入元素的value属性用于检索在输入中输入的值.该值将是一个字符串.

The value property of input elements is used to retrieve the value enters in the input. This value will be a string.

由于要添加数字,因此最好检查输入的内容是否为数字,以避免不必要的错误.可以使用多种方法进行检查,一种方法是在输入的字符串值之前添加"+"号,这会将字符串中的数字转换为数字,然后检查NaN.

Since you want to add numbers, it is better you check if the inputs entered are numbers to avoid unwanted bugs. There are many ways to check this, one I've used it by adding '+' sign in front of the entered string value, this will convert a number in string to a number and then check for NaN.

这是小提琴和代码 https://jsfiddle.net/7sgcmfu8/

<script>  
function f2(){
var a= +document.getElementById("a").value;
var b= +document.getElementById("b").value;
if(!isNaN(a) && !isNaN(b)){
    document.write(a+b);
}else{
    document.write("enter numbers");
}
}
</script>  

Enter A:<input id="a" type="text" name="txt1" ><br>
Enter B:<input id="b" type="text" name="txt2" ><br>
<button type="button" onclick="f2()">Sum Here</button>

这篇关于javascript错误[object HTMLInputElement] [object HTMLInputElement]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆