选择简单计算器中的操作不起作用?

时间:2014-01-30 02:46:53

标签: javascript

我制作了一个简单的Javascript / HTML计算器,您可以输入两个数字并选择一个操作并解决它 问题是,它总是打印“答案:未定义”和“无效操作” 它一直有效,直到我添加了一个选择操作(然后严格添加)

这是我的代码

var back = 0;
var DoIt;
var operation = document.getElementById("Select").value;
function add(num1, num2) {
return num1 + num2;
} 
function multiply(num1, num2) {
return num1 * num2;
} 
function subtract(num1, num2) {
return num1 - num2;
} 
function divide(num1, num2) {
return num1 / num2;
} 
function functions() {
if (back==0) 
{
    var first = document.getElementById("number1").value;
    var second = document.getElementById("number2").value;
    first = parseInt(first);
    second = parseInt(second);
        if (operation=="Add"||operation=="add") 
        {
            var DoIt = add(first, second);
        }
        else if (operation=="Subtract"||operation=="subtract") 
        {
            DoIt = subtract(first, second);
        }
        else if (operation=="Multiply"||operation=="multiply") 
        {
            DoIt = multiply(first, second);
        }
        else if (operation=="Divide"||operation=="divide")
        {
            DoIt = divide(first, second);
        }
        else 
        {
            document.getElementById("Select").value = "Invalid Operation";
        }




    document.getElementById("number1").style.display = 'none';
    document.getElementById("number2").style.display = 'none';
    document.getElementById("Answer").style.display = 'block';
    document.getElementById("Answer").value = "Answer: " + DoIt;
    document.getElementById("write").value = "Go Back";
    back = back+1;
}
else
{
    document.getElementById("Answer").style.display = 'none';
    document.getElementById("number1").style.display = 'inline';
    document.getElementById("number2").style.display = 'inline';
    document.getElementById("write").value = "Go";
    back = 0;
}
}

HTML

<input id="Answer" placeholder="Answer" class="inputs">
<input id="number1" placeholder="First Number" class="inputs">
<br />
<input id="number2" placeholder="Second Number" class="inputs">
<br />
<input id="Select" placeholder="Choose An Operation" class="inputs">
<p id="Texts">Enter Add, Subtract, Multiply, or Divide.</p>
<input type="button" id="write" onclick="functions();" value="Go" class="button">

1 个答案:

答案 0 :(得分:0)

您必须在函数operation中声明变量DoItfunctions()

function functions(){
var operation = document.getElementById("Select").value;
var DoIt;
if (back==0)
// the rest of the function
}

你不应该两次声明变量DoIt。因此,var DoIt = add(first, second);行应该成为DoIt = add(first, second);