2014-09-10 42 views
1

我有一個簡單的JavaScript程序,可以將攝氏溫度轉換爲fahreinheit,反之亦然。但是一個函數不起作用並返回NaN。爲什麼我從JavaScript中獲得NaN功能

<script type="text/javascript"> 
    function CtoF() { 
     c = parseInt(document.getElementById("celsiusTemp").value); 
     fah = c * (9/5) + 32; 
     document.getElementById("resC").innerHTML = fah; 
    } 

    function FtoC() { 
     f = parseInt(document.getElementById("celsiusTemp").value); 
     cel = (f - 32) * (5/2); 
     document.getElementById("resF").innerHTML = cel; 
    } 
</script> 
<body> 
    <form> 
     <p>Insert celsius temperatur: 
      <input type="text" id="celsiusTemp" /> 
      <br> 
     </p> 
     <p>Insert fahrenheit temperatur: 
      <input type="text" id="fahreheitTemp" /> 
      <br> 
     </p> 
     <input type="button" class="btn btn-success" onClick="CtoF()" Value="Calc Fahrenheit" /> 
     <input type="button" class="btn btn-warning" onClick="FtoC()" Value="Calc Celsius" /> 
    </form> 
    <br/> 
    <p>The Result is : 
     <br/> 
     <p>Result celsius to fahreinhet:</p><span id="resC"></span> 

     <p>Result fahreinhet to celsius:</p><span id="resF"></span> 

</body> 

計算攝氏度時)

謝謝爲什麼我得到NaN的!

+0

您可能在'FtoC'函數中指的是'getElementById(「fahreheitTemp」)'... – Vache 2014-09-10 14:25:22

+0

您從哪裏得到NaN?爲什麼你在兩種不同的公式中使用不同的比率進行轉換? – 2014-09-10 14:25:26

回答

6

你可能需要更換:

f = parseInt(document.getElementById("celsiusTemp").value); 

有了:

f = parseInt(document.getElementById("fahreheitTemp").value); 

如果單擊Calc Celsius按鈕,它會試圖從攝氏字段的值。如果這是空的,parseInt將返回NaN

isNaN(parseInt("")) === true 
2

因爲你攝氏度功能是讀取輸入錯誤,因爲你沒有輸入到該輸入當你測試的功能,它是一個空字符串,它parseInt變成不是一個數字。

相關問題