Javascript中的操作错误不正确

时间:2012-03-12 06:56:11

标签: javascript html calculator operation

我在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));
    }
}

1 个答案:

答案 0 :(得分:0)

像这样重写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 - 按钮......