2013-09-01 98 views
3

我試圖找到我的代碼不工作的原因,並且chrome返回了這個錯誤: 未捕獲的ReferenceError:calcMPG未定義... 有人能發現我的錯誤嗎?絕望)javascript錯誤:函數未定義

<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> 
+1

startMileage是不確定的。請填寫完整代碼。 – Dmitry

+0

當我運行這個時,我得到錯誤「未捕獲的ReferenceError:startMileage未定義」,而不是您指定的calcMPG。 –

+1

什麼是'startMileage','endMileage'和'gallUsed'? –

回答

6

你的聲明是錯了,請糾正。

var startMileage = document.calc.startingMileage.value ; 
var endMileage = document.calc.endingMileage.value; 
var gallUsed = document.calc.gallonsUsed.value; 
1
startMileage 

和你的另一右側引用並不意味着什麼,他們是不確定的變量。

給您輸入ID,並獲取從他們的價值觀是這樣的:

var startingMileage = document.getElementById('startingMileage').value; 
+1

應該是'document.getElementById('startingMileage')。value;' –

+0

@PatrickEvans是的,正確的,我在那裏匆匆忙忙。更新。 – Jonast92

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> 
0

入住這裏Fiddle

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; 
    }