为什么我从JavaScript函数中获取NaN

0 javascript

我有一个简单的JavaScript程序,可以将摄氏度转换为fahreinheit,反之亦然.但是一个函数不起作用并返回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>
Run Code Online (Sandbox Code Playgroud)

为什么在计算摄氏度时会得到NaN)

谢谢!!

Cer*_*rus 5

您可能需要更换:

f = parseInt(document.getElementById("celsiusTemp").value);
Run Code Online (Sandbox Code Playgroud)

附:

f = parseInt(document.getElementById("fahreheitTemp").value);
Run Code Online (Sandbox Code Playgroud)

如果单击该Calc Celsius按钮,它将尝试从摄氏度字段中获取值.如果那是空的,parseInt将返回NaN:

isNaN(parseInt("")) === true
Run Code Online (Sandbox Code Playgroud)