javascript - 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。因为第二个条件没有执行。有人知道这段代码有什么问题吗?我错过了什么?
解决方案
您的代码将 设置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);
}
}
推荐阅读
- html - 打印 Perl CSS 和 HTML
- mysql - Oracle DBlink 创建以从 MySql 获取数据
- shell - 通过powershell将打印机添加到打印服务器
- html - html文件输入只选择一个文件
- hangfire - 一次性使用hangfire
- c# - C# 将两个字符串列表与一个模式相交
- python-3.x - 如何在 Python 中匹配日期和时间
- android - 使用 jitpack 构建的库中的错误:无法解析 ':app@debug/compileClasspath' 的依赖关系
- xcode - 如何在 appStore 连接中更新我的应用信息?
- java - resultset.next() 仅显示第一行的输出