javascript - 使用 JavaScript 中的条件以 HTML 格式打印消息

标签 javascript html if-statement

我使用 HTML 和 JavaScipt 创建了一个计算器。计算器可以工作,所以没问题。但是,我想在 html 中编写一条消息,让用户知道如果结果为 NaN,他们必须输入一个变量。虽然我知道我需要使用条件语句,但我不确定如何编码。

这是我的代码:

function calc(){
        var n1 = parseFloat(document.getElementById("n1").value);
        var n2 = parseFloat(document.getElementById("n2").value);
        var oper = document.getElementById("operators").value;

        if( oper === "+"){
            document.getElementById("result").value = n1+n2;
        }
        if( oper === "-"){
            document.getElementById("result").value = n1-n2;
        }
        if( oper === "*"){
            document.getElementById("result").value = n1*n2;
        }
        if( oper === "/"){
            document.getElementById("result").value = n1/n2;
        }
        if( oper === NaN ){
            document.getElementById("Comments").innerHTML= "Write something in the boxes, you silly ass." ;
        }
     }
<input type="text" id="n1"/><br/><br/>
<input type="text" id="n2"/><br/><br> 

<select id="operators">
    <option value="+">+</option> 
    <option value="-">-</option> 
    <option value="X">X</option> 
    <option value="/">/</option> 
</select>

<input type="text" id="result"/> 
 <button onclick="calc();">=</button>
<p id="Comments"></p>

最佳答案

要改进代码,您可以添加 else ifisNaN,如下所示:

function calc(){
        var n1 = parseFloat(document.getElementById("n1").value);
        var n2 = parseFloat(document.getElementById("n2").value);
        var oper = document.getElementById("operators").value;

        if( oper === "+"){
            document.getElementById("result").value = n1+n2;
        } else if( oper === "-"){
            document.getElementById("result").value = n1-n2;
        } else if( oper === "*"){
            document.getElementById("result").value = n1*n2;
        } else if( oper === "/"){
            document.getElementById("result").value = n1/n2;
        } else if( isNaN(oper) ){
            document.getElementById("Comments").innerHTML= "Write something in the boxes, you silly ass." ;
        }
     }
<input type="text" id="n1"/><br/><br/>
<input type="text" id="n2"/><br/><br> 

<select id="operators">
    <option value="+">+</option> 
    <option value="-">-</option> 
    <option value="X">X</option> 
    <option value="/">/</option> 
</select>

<input type="text" id="result"/> 
 <button onclick="calc();">=</button>
<p id="Comments"></p>

关于javascript - 使用 JavaScript 中的条件以 HTML 格式打印消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50994559/

相关文章:

javascript - 使用 Jquery 根据输入(搜索栏)值显示/隐藏 img 元素

javascript - 为什么 window.data 有效而不是 data

javascript - 如何判断字母是否在字符串中-javascript

batch-file - 简单的 IF 语句有超过 1 位的数字吗?

javascript - 使用javascript计算两个日期之间的天数

javascript - Dropzone JS 不是部分 View 中的函数错误

javascript - 使用不同参数的函数重载 JavaScript

用于更改表单边框颜色的 Javascript 不起作用?

html - 地铁风格中的 Div 位置

java - 使用 IF 和 ELSE 语句设置 Enable 或 Disable 而不是 True 或 False