3

我试图找出我的代码不起作用的原因,并且 chrome 出现了这个错误:Uncaught ReferenceError: calcMPG is not defined... 有人能发现我的错误吗?(绝望)

<script type="text/javascript">
    function calcMPG() {
        document.calc.startingMileage.value = startMileage;
        document.calc.endingMileage.value = endMileage;
        document.calc.gallonsUsed.value = gallUsed;
        var MPG = (endMileage - startMileage) / gallUsed;
        if (isNAN(startMileage) || isNAN(endMileage) || isNAN(gallUsed)) alert('please type in numbers only!');
        else document.calc.milesPerGalon.value = MPG;
    }
</script>

<form name="calc">Starting mileage:
    <input type="text" value="0" name="startingMileage" onchange="calcMPG()">
    <br>Ending mileage:
    <input type="text" value="0" name="endingMileage" onchange="calcMPG()">
    <br>Gallons used:
    <input type="text" value="0" name="gallonsUsed" onchange="calcMPG()">
    <br>Miles per galon:
    <input type="text" value="0" name="milesPerGalon">
</form>
4

4 回答 4

6

您的声明是错误的,请更正它们。

var startMileage = document.calc.startingMileage.value ;
var endMileage =  document.calc.endingMileage.value;
var gallUsed =  document.calc.gallonsUsed.value;
于 2013-09-01T18:02:41.770 回答
1
startMileage

而您的其他右侧引用没有任何意义,它们是未定义的变量。

为您的输入提供一个 id 并从它们中获取值,如下所示:

var startingMileage = document.getElementById('startingMileage').value;
于 2013-09-01T18:01:06.510 回答
1

我不知道你为什么这样做,但试试这个:

<script type="text/javascript">
  function calcMPG(){
    var startMileage  = document.calc.startingMileage.value,
        endMileage    = document.calc.endingMileage.value,
        gallUsed      = document.calc.gallonsUsed.value,
        MPG           = (endMileage - startMileage) / gallUsed;

      if(isNaN(startMileage) || isNaN(endMileage) || isNaN(gallUsed)){
        alert('please type in numbers only!');
      } else {
        document.calc.milesPerGalon.value = MPG;
      }
    }
</script>
<form name="calc">
    Starting mileage:<input type="text" value="0" name="startingMileage" onchange="calcMPG()"><br>
    Ending mileage:<input type="text" value="0" name="endingMileage" onchange="calcMPG()"><br>
    Gallons used:<input type="text" value="0" name="gallonsUsed" onchange="calcMPG()"><br>
    Miles per galon:<input type="text" value="0" name="milesPerGalon">
</form>
于 2013-09-01T18:04:12.560 回答
0

在这里检查小提琴

 function calcMPG(){
        var startMileage = document.calc.startingMileage.value;
        var endMileage = document.calc.endingMileage.value;
        var gallUsed = document.calc.gallonsUsed.value;

        var MPG = (endMileage - startMileage) / gallUsed; 

        if(isNaN(startMileage) || isNaN(endMileage) || isNaN(gallUsed))
            alert('please type in numbers only!');
        else 
            document.calc.milesPerGalon.value = MPG;
    }
于 2013-09-01T18:08:41.573 回答