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

Categories

0 votes
285 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));
    }
});

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...