首页 > 解决方案 > javascript的前置条件?

问题描述

我有一个显示start和的计时器按钮stop。当我单击它时,文本变为stop,当我再次单击它时,文本变为start。为了保持状态,然后我写了这样的代码:

start.onclick = function() {
    if (state == 0) {
        state = 1;
        timer();
    }
    if (state == 1) {
        state = 0;
        clearTimeout(t);
    }
}

状态的前提是0。正常情况下,如果状态等于0,它应该工作,然后状态将变为1并执行timer()。如果 state 等于 1,state 将变为 0,并执行 clearTimeout()。但我不知道为什么它在 javascript 中不能这样工作。然后我像这样更改代码:

start.onclick = function() {
    if (state == 0) {
        timer();
    }
    if (state == 1) {
        state = 0;
        clearTimeout(t);
    }
    state = 1;
}

然后它起作用了,执行 timer() 并将状态更改为 1,但是当我再次尝试启动按钮时,没有任何效果。我检查状态,然后状态为1。因为第二个条件没有执行。有人知道这段代码有什么问题吗?我错过了什么?

标签: javascriptstate

解决方案


您的代码将 设置state为 1,如果它是 0。

这使得第二个条件为if真,因此它的代码也被执行。因此,两个 if 都在state为 0 时执行。

使用else if喜欢

start.onclick = function () {
    if (state == 0) {
        state = 1;
        timer();
    } else if (state == 1) { <=== see the difference in this line
        state = 0;
        clearTimeout(t);
    }
}

推荐阅读