Быстрое решение состоит в том, чтобы добавить дополнительную строку в функцию submit001
, прежде чем какой-либо код уже имеет:
if (document.getElementById("answer001").textContent === "Correct") {
goToNextQuestion();
}
А в функции gotoNextQuestion
вы должны убедиться, чтоочистить текстовое содержимое (удалить «Исправить»).
Но имейте в виду, что событие keydown не срабатывает на элементе input
, когда вы его скрываете, поэтому вам следует прослушать это событие в документе.
Еще лучше было бы использовать переменную для этого состояния вместо зависимости от того, что находится в документе HTML.
Вот реализация, которая использует addEventListener
вместо того, чтобы иметь код JS внутриваши HTML-теги.Обратите внимание, как он слушает на уровне документа.Также лучше использовать свойство события key
, а не keyCode
.
Новая переменная execOnEnter
определяет, какую функцию выполнять в зависимости от состояния «игры».В коде он изменяется на submit001
или goToNextQuestion
:
var country = ["Italy", "Spain", "Portugal", "France"];
var capital = ["rome", "madrid", "lisbon", "paris"];
var random001 = Math.floor(Math.random() * country.length);
document.getElementById("country").textContent = country[random001];
var execOnEnter = submit001;
document.addEventListener("keydown", function (e) {
if (e.key !== "Enter") return;
execOnEnter();
});
function submit001() {
var b = input001.value.toLowerCase();
var text;
if (b === capital[random001]) {
text = "Correct!";
hideAndShowDIV();
execOnEnter = goToNextQuestion;
} else {
text = input001.value.bold() + " is not correct!";
}
document.getElementById("input001").value = "";
document.getElementById("answer001").innerHTML = text;
}
function hideAndShowDIV() {
var x = document.getElementById("userInput");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
function goToNextQuestion() {
document.getElementById("answer001").innerHTML = "";
random001 = Math.floor(Math.random() * country.length);
document.getElementById("country").innerHTML = country[random001];
hideAndShowDIV()
execOnEnter = submit001;
document.getElementById("input001").focus();
}
<p id="message001">What is the capital of <text id="country"></text>?</p>
<div id="userInput" style="display:block">
<input type="text" id="input001" autofocus>
</div>
<p id="answer001"></p>