-4

我正在尝试在 js 中计算一个简单的乘法,如下所示:
A * B = C
D * E = F
G * H = I
总计 = C + F + I

然而,总数比预期的要大得多。我的乘法有问题还是我从页面中读取的值不正确?

下面是我的代码:

<html>
<head>
<script>
  calculate = function(totalElement)
  {
      if (totalElement)
      {
          var calculation  = '';
          var overall = '';
          var fields = new Array();
          var theElement = document.getElementById(totalElement);
          var userInputs = myform.elements;
          var the_type = '';
          for (var f = 0; f < userInputs.length; f++)
          {
              if (userInputs[f].className=='special_value')
              {
                 if(userInputs[f].value != "")
                 {
                     document.getElementById("price4").value+=+userInputs[f].value;

                 }           

              }
          }


      }
  }
</script>
</head>
<body>
<form name="myform">
A<input onKeyPress="calculate('total');" onBlur="calculate('total');" class="special_value" value="" type="text" name="price"> 
B<input onKeyPress="calculate('total');" onBlur="calculate('total');" class="special_value" type="text" value="" name="price2"> 
C<input onKeyPress="calculate('total');" onBlur="calculate('total');" class="special_value" type="text"value=""  name="price4" id="price4"> <Br/>
D<input onKeyPress="calculate('total');" onBlur="calculate('total');" class="special_value" value="" type="text" name="price5"> 
E<input onKeyPress="calculate('total');" onBlur="calculate('total');" class="special_value" type="text" value="" name="price6"> 
F<input onKeyPress="calculate('total');" onBlur="calculate('total');" class="special_value" type="text"value=""  name="price7" id="price7"> <Br/>
Total<input class="special_value" value="" id="total" type="text" name="total"> <Br/>
<!-- <div id="total"></div> -->
<input onClick="calculate('total');" type="button" name="button" value="re-calculate">
</form>
</body>
</html>
4

1 回答 1

5

document.getElementById("price4").value是一个字符串。您可能会连接字符串,而不是对它们进行数学运算。

尝试:parseFloat(document.getElementById("price4").value)

于 2013-03-05T19:44:39.620 回答