HTML javascript 函数问题。[object HTMLInputElement] 错误输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26205691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML javascript function issue. [object HTMLInputElement] error output
提问by Xfmym
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].
我正在尝试制作一个简单的 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>
Any help would be appreciated. I tried changing .innerHTMLto .valuealready but then I get nothing at all as a result.
任何帮助,将不胜感激。我已经尝试更改.innerHTML为,.value但结果我什么也没得到。
回答by JME
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/.
这是一个有效的小提琴:http: //jsfiddle.net/JohnnyEstilles/ex09fx7k/。
回答by Oriol
Some fixes:
一些修复:
- You are adding up the inputs elements instead of their
value. - To convert its string value to a number, you can use unary
+. - Instead of inline event listeners, better use
addEventListener.
- 您正在添加输入元素而不是它们的
value. - 要将其字符串值转换为数字,可以使用 unary
+。 - 而不是内联事件侦听器,最好使用
addEventListener.
var a = document.getElementById('varA'),
b = document.getElementById('varB'),
result = document.getElementById("testResult");
document.getElementById('add').addEventListener('click', function() {
addNumbers(a.value, b.value);
});
function addNumbers(n1, n2){
result.textContent = +n1 + +n2;
}
<input type="text" value="15" id="varA">
<input type="text" value="30" id="varB">
<input type="button" id="add" value="Add">
<h1 id="testResult"></h1>

