Javascript中存在不正确的操作错误

Incorrect Operation error in Javascript

本文关键字:操作 错误 不正确 存在 Javascript      更新时间:2023-09-26

我用javascript创建了一个简单的计算器,我将在其中输入2个数字,然后选择一个运算并执行该运算,但在这段代码中,唯一显示正确答案的是"+""-"

这是代码

var fnum;
var secondNum;
var operation;
function msg(val) {
fnum = document.getElementById("fnumtext").value += val;
}
function showOperation(oper) 
{
    document.getElementById("fnumtext").value = "";
    document.getElementById("operation").value = oper;
    operation = oper;
}
function equal() {
    secondNum = document.getElementById("fnumtext").value;
    var num1 = parseInt(fnum) 
    var num2 = parseInt(secondNum);
    if(document.getElementById("operation").value == "+"){
    document.getElementById("fnumtext").value = parseInt(fnum) + parseInt(secondNum);
    }else if(document.getElementById("operation").value == "-"){
        document.getElementById("fnumtext").value = num1-num2;
    }else if(document.getElementById("operation").value == "*"){
        document.getElementById("fnumtext").value = num1 * num2;
    }else if(document.getElementById("operation").value == "/"){
        document.getElementById("fnumtext").value = (parseInt(fnum) / parseInt(secondNum));
    }
}

像这样重写msg()

function msg(val) {
if(!secondNum && fnum)
    secondNum = document.getElementById("fnumtext").value += val;
if(!fnum)
    fnum = document.getElementById("fnumtext").value += val;
}

然后将下面的行作为最后三行添加到equal()

function equal() {
    ...
    fnum=false;
    secondNum=false;
    return;
}

这只是一个建议,我相信当你开发应用程序时,你会找到更好的方法来完成这一切。至少它需要一个C按钮。。。