我正在寫一個溫度轉換器,似乎無法弄清楚我的javascript有什麼問題。我甚至無法讓它提醒「跑步」。我的函數曾被稱爲轉換,但我想也許這是js的關鍵詞,所以我將它改爲tempConvert。代碼應該可以相互轉換溫度。我的JavaScript不工作在我的溫度轉換器
兩個測試我使用的是
32F = 0C
和
72F = 22.22222...C
它工作在提示和警報消息很好,現在我想用輸入框。
<!DOCTYPE html />
<html>
<head>
<script type="text/javascript">
function tempConvert(){
alert("running.");
var f = document.getElementById("fahrenheit").value; //Gets the value for farenheit.
var c = document.getElementById("celsius").value; //Gets the value for celsius
var tf = isNumber(f); //Test if the value of f is a number.
var tc = isNumber(c); //Test if the value of c is a number.
if (tf = true){
//if f is a number run this
c = (f-32)/1.8; //conversion from f to c
document.getElementById("celsius").value = c; //sets the value of the celsius input box to c.
alert(c);
} else if (tc = true){
// does the same as previous if statement, switching temperature types.
f = (c+32)*1.8;
document.getElementById("fahrenheit").value = f;
} else {
alert("One of your inputs are invalid.");
// alerts the user if f and c are not a number.
}
}
funcion isNumber(test){ //A custom function(method) used to test if f or c is a number
return !isNaN(parseFloat(test)) && isFinite(test); //copied from another article in stackoverflow (http://stackoverflow.com/questions/6449611/how-to-check-whether-a-value-is-a-number-in-javascript-or-jquery)
}
</script>
</head>
<body>
<input id="fahrenheit" placeholder="fahrenheit"></input> =
<input id="celsius" placeholder="celsius"></input>
<input type="button" value="convert" onclick="tempConvert()" />
</body>
</html>
您是否收到任何錯誤?或者函數甚至沒有調用。 – Thangadurai
函數拼寫錯誤在follwoing行中:funcion isNumber(test); –
抱歉代碼沒有執行。 –