1

伙计们。我正在尝试使用 jQuery 创建一个具有基本操作的基于 Web 的计算器。我已经实现了加法操作。现在,我迷上了减法。

这是单击减号按钮时的代码片段:

$("#btnSub").click(function () {
    holdValue = $("#result").val();
    currentValue = $("#result").val("0");

    flagSub = "1";
    flagNotEmpty = "0";
    flagDecimal = "0";
});

这是单击等号按钮时的代码片段:

$("#btnEquals").click(function () {
    if (flagNotEmpty == "0") {
        alert("Missing Value.");
    } else {
        if (flagAdd == "1") {
            currentValue = $("#result").val();
            var output = parseFloat(holdValue) + parseFloat(currentValue);
            $("#result").val(parseFloat(output));
        } else if (flagSub == "1") {
            currentValue = $("#result").val();
            var output2 = parseFloat(holdValue) - parseFloat(currentValue);
            $("#result").val(parseFloat(output2));
        }
    }

    flagSub = "0";
    flagAdd = "0";
    flagNotEmpty = "0";
    flagDecimal = "0";
});

变量功能:

  1. flagSub:用于确定选择的操作是减法

  2. flagNotEmpty: 用于判断选择运算符后是否按下数字。如果在运算符按钮后单击等号,则显示错误消息。

  3. flagDecimal:用于告诉程序已经输入了一个小数。显示小数点重复的错误消息。

Problem with this program is that it cannot perform subtraction when it is the first operation you do. That is, when the browser loads the UI and you do subtraction, nothing happens. BUT, when you do, for example, click 1 + 2 = then the program displays 3 in the textbox. Without refreshing the page, click - 10 =. Difference is displayed.

To start from the beginning, please refresh the page; will just add the CLEAR button after I am done with all the operations.

Just want to know what is wrong with my algorithm. For the complete code with html and css, here is its fiddle.

By the way, I have just started learning jQuery so please forgive me for the kind of messy and might be inefficient way of coding. Help is really much appreciated. Thanks in advance.

4

1 回答 1

0

flagAdd needs to be initialized, you can alter the btnSub handler to do that

$("#btnSub").click(function () {
    holdValue = $("#result").val();
    currentValue = $("#result").val("0");

    flagAdd = "0";
    flagSub = "1";
    flagNotEmpty = "0";
    flagDecimal = "0";
});

alternatively you could initialize it in the document ready handler Fiddle

于 2013-01-19T09:47:34.733 回答