如果表达式在JavaScript中与HTML(可选)按钮在一个函数中

If-expression in JavaScript with HTML (optional) button in one function

本文关键字:一个 函数 按钮 可选 表达式 JavaScript 中与 HTML 如果      更新时间:2023-09-26

我正在创建一个HTML表,其中包含必须填充的字段,但我想让其中一个字段是可选的。我的代码是这样的:

name.html

...
<table>
    <tr>
    <td>A number:</td>
    <td><input id="numb1" type="text"/></td>
    </tr>
    <tr>
    <td>Anoder number (optional)</td>
    <td><input id="numb2" type="text"></td>
    </tr>
</table>
<input type="button" value="Click" onclick="forfun()"/>
<pre id="result">
Result
</pre>  
 ...

在我的jaava.js中,我想使用一个if-else表达式,定义如果可选字段不为空,那么变量应该取写在字段中的数字的值。

    function forfun() {
    var numberOne=document.getElementById("numb1").value;
    numberOne =parseFloat(numberOne); // numberOne is now really a number
    var numberTwo=document.getElementById("numb2").value;
    numberTwo=parseFloat(numberTwo);
        ...

    if(numberTwo==NaN) { //Here comes the problem, I tried also with 
    //undefined and ==0, but after pressing the button, I become the results
    //of my functions in this loop with result NaN
    numberTwo=2; 
    //and so on
        ...
    }
    }else {
    //After I fill the second field, everything here is ok 
    }

if后面的括号之间应该写些什么?你能给我一些想法吗?

NaN的比较总是返回false,因此即使是NaN == NaN也会返回false。相反,使用内置的isNaN()功能:

if (isNaN(numberTwo)) {