HTML javascript函数问题. [object HTMLInputElement]错误输出 [英] HTML javascript function issue. [object HTMLInputElement] error output

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

问题描述

我正在尝试制作一个带有两个文本框和一个单击按钮时将两个数字加在一起的按钮的简单html页面.在我的输出中,我只得到[object HTMLInputElement].

 function addNumbers(A, B){
  var answer = A + B;
  document.getElementById("testResult").innerHTML = answer;
} 

 <input type="text" value="15" id="varA">
<input type="text" value="30" id="varB">
<input type="button" value="Add" onclick="addNumbers(varA, varB)">
<h1 id="testResult"></h1> 

任何帮助将不胜感激.我已经尝试将.innerHTML更改为.value,但是结果一无所获.

解决方案

我假设您需要数学和而不是字符串连接.在这种情况下,您可以使用以下代码:

基于评论的更新:

 function addNumbers(elem1, elem2) {
  var a = document.getElementById(elem1).value;
  var b = document.getElementById(elem2).value;
  var c = Number(a) + Number(b);
  document.getElementById("testResult").innerHTML = c;
} 

 <input type="text" value="15" id="varA">
<input type="text" value="30" id="varB">
<input type="button" value="Add" onclick="addNumbers('varA', 'varB')"></input>
<h1 id="testResult"></h1> 

这是一个正在工作的小提琴: http://jsfiddle.net/JohnnyEstilles/ex09fx7k/. /p>

I am trying to make a simple html page with two text boxes and an a button that adds the two numbers together when clicked. In my output, I am only getting [object HTMLInputElement].

function addNumbers(A, B){
  var answer = A + B;
  document.getElementById("testResult").innerHTML = answer;
}

<input type="text" value="15" id="varA">
<input type="text" value="30" id="varB">
<input type="button" value="Add" onclick="addNumbers(varA, varB)">
<h1 id="testResult"></h1>

Any help would be appreciated. I tried changing .innerHTML to .value already but then I get nothing at all as a result.

解决方案

I assume you want the mathematical sum and not the string concatenation. If that's the case, you can use the following:

UPDATE based on comment:

function addNumbers(elem1, elem2) {
  var a = document.getElementById(elem1).value;
  var b = document.getElementById(elem2).value;
  var c = Number(a) + Number(b);
  document.getElementById("testResult").innerHTML = c;
}

<input type="text" value="15" id="varA">
<input type="text" value="30" id="varB">
<input type="button" value="Add" onclick="addNumbers('varA', 'varB')"></input>
<h1 id="testResult"></h1>

Here's a working Fiddle: http://jsfiddle.net/JohnnyEstilles/ex09fx7k/.

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

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