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;
};
答案 0 :(得分:0)
将parseFloat之后的值存储到错误的变量中。您基本上只是覆盖了相同的变量data
,而且您也没有初始化变量number1
和number2
。
应该是这样的:
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;
};
答案 1 :(得分:0)
number1
&& number2
)。parseFloat
的工作方式。 parseFloat
接受一个参数(一个字符串)并返回一个浮点数(如果有的话)。试试这个:
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;
};
答案 2 :(得分:0)
您正在文档的input元素上执行“parseFloat”函数,其id为“number1”和“number2”,而不是您键入的实际值。您无法将文档的输入文本框转换为浮动文件。此外,您使用变量“data”两次,但是您希望将输入的内容的值存储到number1框中,并将其添加到number2框中键入的内容中,并将这两个值添加到您需要两个变量的位置。然后oyu可以添加这两个并将其分配给“total”变量。
我认为您的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;
};