我正在创建一个程序,该程序需要处理Enter键的三个连续按键。我的第一个eventListener按计划工作。但是,当用户输入不正确,并且程序移至第二个eventListener时,程序将始终运行else语句,而不管用户输入是否正确。我再次尝试包含一个变量,以捕获第二个eventListener的用户输入(认为它仍在读取第一个用户输入),但是结果没有什么不同。
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Enter Missing Text</title>
</head>
<body>
<p id="quote"></p>
<p id="correctResponse"></p>
<p id="incorrectResponse"></p>
<script>
let quote = ['For score and', '7', 'years ago.'];
let helper = ' ';
for (i = 0; i < quote.length; i++) {
if (i === 1) {
quote[1] = "<input type='text' id='txtBox'><br>";
}
helper += quote[i];
}
document.getElementById('quote').innerHTML = helper;
document.getElementById('txtBox').focus();
document.addEventListener('keyup', function(e) {
if (e.keyCode === 13) {
var userInput = document.createElement('foo');
userInput.textContent = txtBox.value;
if (userInput.textContent == '7' || userInput.textContent == 'seven') {
document.getElementById('correctResponse').innerHTML = 'awesome.';
} else {
document.getElementById('incorrectResponse').innerHTML = "sorry. try again";
document.getElementById('txtBox').value = " ";
document.getElementById('txtBox').focus();
}
document.addEventListener('keyup', function(e) {
if (e.keyCode === 13) {
var userInput = document.createElement('foo');
userInput.textContent = txtBox.value;
if (userInput.textContent == '7' || userInput.textContent == 'seven') {
document.getElementById('correctResponse').innerHTML = 'awesome.';
} else {
document.getElementById('incorrectResponse').innerHTML = "give it one more try";
document.getElementById('txtBox').value = " ";
document.getElementById('txtBox').focus();
}
}
});
}
});
</script>
</body>
</html>
答案 0 :(得分:2)
如果答案有误,您可以删除上一个侦听器并添加下一个侦听器:
(7
以外的任何输入值都将在处理程序中循环)
const result = document.getElementById('result');
function isEnter(event) {
return event.keyCode === 13
}
function f1(event) {
if (isEnter(event)) {
if (event.target.value !== '7') {
result.innerText = 'wrong 1';
event.target.addEventListener('keyup', f2);
event.target.removeEventListener('keyup', f1);
} else {
result.innerText = 'right 1';
}
}
}
function f2(event) {
if (isEnter(event)) {
if (event.target.value !== '7') {
result.innerText = 'wrong 2';
event.target.addEventListener('keyup', f3);
event.target.removeEventListener('keyup', f2);
} else {
result.innerText = 'right 2';
}
}
}
function f3(event) {
if (isEnter(event)) {
if (event.target.value !== '7') {
result.innerText = 'wrong 3';
event.target.addEventListener('keyup', f1);
event.target.removeEventListener('keyup', f3);
} else {
result.innerText = 'right 3';
}
}
}
document.getElementById('arrr').addEventListener('keyup', f1);
<input type="text" id='arrr'>
<p id='result'></p>