【问题标题】:javascript error [object HTMLInputElement][object HTMLInputElement]javascript 错误 [对象 HTMLInputElement] [对象 HTMLInputElement]
【发布时间】:2017-05-04 02:59:48
【问题描述】:

我正在练习 java 脚本代码,但在实现此代码时遇到问题。

<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] 的错误。

【问题讨论】:

标签: javascript html


【解决方案1】:
<html>
<body>
<script>  
function f2(){
var a=parseInt(document.getElementById("a").value);
var b=parseInt(document.getElementById("b").value);
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>

【讨论】:

  • parseInt()? OP 说的是“数字”,而不是“整数”。
【解决方案2】:

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

由于您要添加数字,因此最好检查输入的输入是否为数字以避免不必要的错误。 有很多方法可以检查这一点,我用过的方法是在输入的字符串值前面添加“+”号,这会将字符串中的数字转换为数字,然后检查 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>

【讨论】:

  • 很好的解决方案 +1 从我身边击中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-15
  • 2014-05-22
相关资源
最近更新 更多