[英]Can't figure out whats wrong in the javascript portion of code
document.getElementById('go').onclick = function() {
var data = document.getElementById('number1').value;
data = parseFloat(number1);
var data = document.getElementById('number2').value;
data = parseFloat(number2);
var total = number1 + number2;
document.getElementById('result').value = total;
};
You store the value after the parseFloat into wrong variable.您将 parseFloat 之后的值存储到错误的变量中。 You're basically just overriding the same variable data
, and also you did not initialize variables number1
and number2
.您基本上只是覆盖了相同的变量data
,而且您没有初始化变量number1
和number2
。
It should be like this:应该是这样的:
document.getElementById('go').onclick = function() {
var number1 = document.getElementById('number1').value;
number1 = parseFloat(number1);
var number2 = document.getElementById('number2').value;
number2 = parseFloat(number2);
var total = number1 + number2;
document.getElementById('result').value = total;
};
number1
&& number2
).您正在使用尚未定义的变量( number1
&& number2
)。parseFloat
works.这不是parseFloat
工作方式。 parseFloat
take an argument (a string) and return a float if any. parseFloat
接受一个参数(一个字符串)并返回一个浮点数(如果有)。Try this:尝试这个:
document.getElementById('go').onclick = function() {
var data = document.getElementById('number1').value;
var number1 = parseFloat(data); // parse the data and store the result in number1
data = document.getElementById('number2').value; // no need to redeclare data
var number2 = parseFloat(data); // parse the data and store the result in number2
var total = number1 + number2;
document.getElementById('result').value = total;
};
You are doing the "parseFloat" function on the document's input element whose ids are "number1" and "number2" instead of the actual values that you typed into them.您正在对文档的输入元素执行“parseFloat”函数,其 id 为“number1”和“number2”,而不是您输入的实际值。 You can't usefully turn a document's input textbox into a float.您不能有效地将文档的输入文本框转换为浮点数。 Also, you use the variable "data" twice, but you want to store the value of whatever is typed into the number1 box, and add that to whatever is typed into the number2 box, and add both those up so you need two variables.此外,您两次使用变量“data”,但您想存储输入到 number1 框中的任何值,并将其添加到输入到 number2 框中的任何值,然后将它们相加,因此您需要两个变量。 Then oyu can add those two up and assign that to the "total" variable.然后 oyu 可以将这两个相加并将其分配给“total”变量。
I assume your HTML is similar to this:我假设您的 HTML 与此类似:
<input id="number1" type="text" /> <br><input id="number2" type="text" /> <br><input id="go" type="button" value="Add Up" /> <br><input id="result" type="text" />
document.getElementById('go').onclick = function () { var number1Value = document.getElementById('number1').value; number1Value = parseFloat(number1Value); var number2Value = document.getElementById('number2').value; number2Value = parseFloat(number2Value); var total = number1Value + number2Value; document.getElementById('result').value = total; };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.