簡體   English   中英

在 JavaScript 中使用 function 轉換溫度時,如何消除 NaN 錯誤?

[英]How do I get rid of the NaN error when converting temperature with a function in JavaScript?

我一直在嘗試制作一個 JS 華氏溫度到攝氏溫度的轉換器,出於某種原因,每當我輸入一個數字並經過 function 時,它會吐出一個NaN ,其中溫度應該為 go。

編輯:在“ftemp”和“ctemp”之后的“值”中添加

編輯:我刪除了 ftemp 和 ctemp 中的值,而是嘗試在 function 本身中訪問它們,就像兩個人回答的那樣,現在工作正常。

 function ftoc(ft) { c = ft * (9 / 5) + 32; return c; } function ctof(ct) { f = (c - 32) / (9 / 5); return f; } button1 = document.getElementById("ftempsubmit"); button2 = document.getElementById("ctempsubmit"); fvalue = document.getElementById("ftemp").value; cvalue = document.getElementById("ctemp").value; fpopup = document.getElementById("fpopup"); cpopup = document.getElementById("cpopup"); button1.onclick = function() { cpopup.value = ftoc(fvalue); }; button2.onclick = function() { fpopup.value = ctof(cvalue); };
 <input type="text" id="ftemp" placeholder="Enter F" /> <button id="ftempsubmit">Submit F</button> <br /> <br /> <input id="cpopup" /> <br /> <br /> <input type="text" id="ctemp" placeholder="Enter C" /> <button id="ctempsubmit">Sumbit C</button> <br /> <br /> <input id="fpopup" />

您不是將輸入的實際value發送,而是將 HTML 元素發送到您的 function,這將拋出NaN

我還將type=text更改為type=number ,因為您將僅使用integer進行conversion

在您的 function ctof中,您在ct處獲得參數,但僅在進行計算時才使用c ,這意味着它將拋出c未定義的錯誤。

現場演示:

 function ftoc(ft) { var c = ft * (9 / 5) + 32; return c; } function ctof(ct) { var f = (ct - 32) / (9 / 5); return f; } button1 = document.getElementById("ftempsubmit"); button2 = document.getElementById("ctempsubmit"); fvalue = document.getElementById("ftemp"); cvalue = document.getElementById("ctemp"); fpopup = document.getElementById("fpopup"); cpopup = document.getElementById("cpopup"); button1.onclick = function() { cpopup.value = ftoc(+fvalue.value); }; button2.onclick = function() { fpopup.value = ctof(+cvalue.value); };
 <!DOCTYPE html> <html> <head></head> <body> <input type="number" id="ftemp" placeholder="Enter F" /> <button id="ftempsubmit">Submit F</button> <br /> <br /> <input id="cpopup" /> <br /> <br /> <input type="number" id="ctemp" placeholder="Enter C" /> <button id="ctempsubmit">Sumbit C</button> <br /> <br /> <input id="fpopup" /> <br /> <br /> <script> </script> </body> </html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM