如何使循环等待用户操作并根据用户输入跳出循环
How to make loop wait for user action and based on user input break out of loop
我想让循环等待用户输入并基于用户输入。我想继续迭代到下一个增量值或跳出循环,但无论输入如何以及何时给出输入,循环都会完成一整圈。它再次运行内部循环两次,而我希望每个 loop/revolution 都有用户输入,并基于此,我可以继续或中断循环。
for (i = 0; i < 1; i++) {
console.log(i);
for (x = 0; x <= 1; x++) {
console.log("Before Event = " + x);
document.querySelector(".top-bar").addEventListener("click", function(event) {
var z = event.key; // Will be some key inalid input
var a = "A";
console.log("After Event = " + x);
if (a !== z) {
console.log("Expected A but Clicked = " + z);
}
console.log("Outside loop = " + x);
});
}
}
控制台日志:
0
Before Event = 0
Before Event = 1
undefined
After Event = 2
Expected A but Clicked = undefined
Outside loop = 2
After Event = 2
Expected A but Clicked = undefined
Outside loop = 2
很难说出你想要完成什么,所以我猜测了一下。首先,您不能将 for 循环与输入事件结合使用。相反,您只需拥有该事件并跟踪它被使用的次数。要捕获按键,请使用 keydown
事件。我使用了一个名为 wrong
的计数器并在 console.log 中将其递增为 ++wrong
let wrong = 0
document.querySelector(".top-bar").addEventListener("keydown", function(event) {
let z = event.key
if (z !== "A") {
console.log("Expected A but Clicked = " + z + ". You've gotten " + ++wrong + " wrong so far");
} else console.log("RIGHT!")
});
input a letter: <input class='top-bar' />
我想让循环等待用户输入并基于用户输入。我想继续迭代到下一个增量值或跳出循环,但无论输入如何以及何时给出输入,循环都会完成一整圈。它再次运行内部循环两次,而我希望每个 loop/revolution 都有用户输入,并基于此,我可以继续或中断循环。
for (i = 0; i < 1; i++) {
console.log(i);
for (x = 0; x <= 1; x++) {
console.log("Before Event = " + x);
document.querySelector(".top-bar").addEventListener("click", function(event) {
var z = event.key; // Will be some key inalid input
var a = "A";
console.log("After Event = " + x);
if (a !== z) {
console.log("Expected A but Clicked = " + z);
}
console.log("Outside loop = " + x);
});
}
}
控制台日志:
0
Before Event = 0
Before Event = 1
undefined
After Event = 2
Expected A but Clicked = undefined
Outside loop = 2
After Event = 2
Expected A but Clicked = undefined
Outside loop = 2
很难说出你想要完成什么,所以我猜测了一下。首先,您不能将 for 循环与输入事件结合使用。相反,您只需拥有该事件并跟踪它被使用的次数。要捕获按键,请使用 keydown
事件。我使用了一个名为 wrong
的计数器并在 console.log 中将其递增为 ++wrong
let wrong = 0
document.querySelector(".top-bar").addEventListener("keydown", function(event) {
let z = event.key
if (z !== "A") {
console.log("Expected A but Clicked = " + z + ". You've gotten " + ++wrong + " wrong so far");
} else console.log("RIGHT!")
});
input a letter: <input class='top-bar' />