0
function calculate()
{
var num1 = document.getElementById("input1").value;
var num2 = document.getElementById("input2").value;
var operator = document.getElementById("operation");
var totalNum = document.getElementById("total");
if (operator == "+")
{
    parseDouble(totalNum = num1 + num2);
}
else if(operator == "-")
{
    parseDouble(totalNum = num1 - num2);
}
total.value = totalNum;
}

我的输出是 [object HTMLInputElement]。如何区分数学运算??

4

2 回答 2

0

您的代码不会给出意外结果,因为它无法区分数学运算。代码中还有其他一些错误。

function calculate()
{
  var num1 = parseDouble(document.getElementById("input1").value);
  var num2 = parseDouble(document.getElementById("input2").value);
  var op = document.getElementById("operation").value;
  var total = document.getElementById("total");
  if (op == "+")
  {
    total.value = num1 + num2;
  }
  else if(op == "-")
  {
    total.value = num1 - num2;
  }
}
于 2013-10-26T10:08:09.160 回答
0
var totalNum = document.getElementById("total");

设置totalNum为对字段的引用。我相信你想要它

var total = document.getElementById("total");

这里。另外,你需要

var operator = document.getElementById("operation").value;

注意.value最后。没有这个, operationis not "+"or "-", 所以if's 不会被执行。因此,以某种方式引用的字段total将获得totalNum(-> totalNum.toString()) 的值,这是对结果字段的引用,并变为[Object HTMLInputElement].

于 2013-10-26T10:09:46.307 回答