Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

javascript - Why when I clicked on subtract or multiply button still doing the add function?

My if statements don't work because I said to the statements to make subtract, if subtractOp (subtract button is clicked) were click and this operator still doing add function.

let firstValue;
let secondValue;

addOp.addEventListener('click', function() {
    firstValue = Number(outPut.innerText);
    outPut.innerText = '';
});

subtractOp.addEventListener('click', function() {
    firstValue = Number(outPut.innerText);
    outPut.innerText = '';
});

multiplyOp.addEventListener('click', function() {
    firstValue = Number(outPut.innerText);
    outPut.innerText = '';
});

equals.addEventListener('click', function() {
    secondValue = Number(outPut.innerText);
    if(addOp) {
        outPut.innerText = add(firstValue, secondValue);
        console.log(add(firstValue, secondValue));
    } else if(subtractOp) {
        outPut.innerText = subtract(firstValue, secondValue);
        console.log(subtract(firstValue, secondValue));
    } else if(multiplyOp) {
        outPut.innerText = multiply(firstValue, secondValue);
        console.log(multiply(firstValue, secondValue));
    }
});
question from:https://stackoverflow.com/questions/65516654/why-when-i-clicked-on-subtract-or-multiply-button-still-doing-the-add-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That's because your if/else statement in the equals handler is wrong.

    if(addOp) {
        outPut.innerText = add(firstValue, secondValue);
        console.log(add(firstValue, secondValue));
    } else if(subtractOp) {
        outPut.innerText = subtract(firstValue, secondValue);
        console.log(subtract(firstValue, secondValue));
    } else if(multiplyOp) {
        outPut.innerText = multiply(firstValue, secondValue);
        console.log(multiply(firstValue, secondValue));
    }

if(addOp) always returns true because addOp is an HTML element. You need to add booleans to determine what operation you wish to perform.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...