javascript 为什么IF语句在这里不起作用?

c9x0cxw0  于 2023-03-16  发布在  Java
关注(0)|答案(1)|浏览(176)

我正在做一个初学者的小项目。if语句不起作用
if语句

const value = document.getElementById("value")
const btnDecrease = document.querySelector(".decrease")
const btnReset = document.querySelector(".reset")
const btnIncrease = document.querySelector(".increase")

let count = 0

btnDecrease.addEventListener("click", function() {
    count--
    value.textContent = count
   
})

btnIncrease.addEventListener("click", function() {
    count++
    value.textContent = count
   
})

btnReset.addEventListener("click", function() {
    count = 0
    value.textContent = count
})

if (count > 0) {
    value.style.color = "Green";
} else if (count < 0) {
    value.style.color = "red";
} else {
    value.style.color = "#222"
}

如果计数为负值,我应该将其变为红色,如果为正值,则变为绿色

hsvhsicv

hsvhsicv1#

当前if语句只运行一次,然后才输入任何值。
将其提取到函数中,并在每次计数更改后调用它。

function update() {
    if (count > 0) {
        value.style.color = "Green";
    } else if (count < 0) {
        value.style.color = "red";
    } else {
        value.style.color = "#222"
    }
    value.textContent = count;
}
btnDecrease.addEventListener("click", function() {
    count--;
    update();
});
btnIncrease.addEventListener("click", function() {
    count++
    update();
});
btnReset.addEventListener("click", function() {
    count = 0;
    update();
});

相关问题