为什么在我运行代码后循环使用check()而不是playQuiz(),问题循环也无法正常进行

问题描述 投票:0回答:1
     <p id = "question"> </p>
     <input id ="yourAnswer" type = "text" placeholder="Write your answer">
     <button id = "checkAnswer" onclick = "check()"> Submit</button>

这是我在body标记内的html代码

var quiz = [
            ["Who lived at 221B, Baker Street, London? ", "Sherlock Holmes"],
            ["When did the First World War start? ", "1914"],
            ["Who wrote Julius Caesar, Macbeth and Hamlet? ", "Shakespeare"],
            ["Who invented the telephone?", "Bell"],
            ["Where is the smallest bone in the body?", "ear"]
           ];


var score = 0;
var wrongAnswer = 0;

playQuiz(quiz);

function playQuiz(quiz) {

    for (var i = 0, question, answer, max = quiz.length; i < max; i++) {
        document.getElementById("question").innerHTML = quiz[i][0]; 
        question = quiz[i][0];
        console.log(question);     
        answer = document.getElementById("yourAnswer").value;
        var expectedAnswer = quiz[i][1];
        ask(question);
        check(answer, expectedAnswer);

    }

    gameOver();

}

我的for循环在点击提交按钮后无法更改问题。问题显示在控制台日志中,但不会更改我的document.getElementById(“ question”)。innerHTML上的问题。

function ask(question) {
    return document.getElementById("question").innerHTML = question;
}

我运行程序后,程序就直接转到这里

function check(answer, expectedAnswer) {

    if (answer === expectedAnswer) { // quiz[i][1] is the ith answer   
        alert("Correct!"); // increase score by 1  
        score++;
    } else {
        alert("Wrong!");
        wrongAnswer++;
    }
}

 function gameOver(){   
    alert(`Game Over, you scored ${score} points and ${wrongAnswer} wrong answers`);  
} 


```
javascript arrays label
1个回答
0
投票

据我所知,您希望一个个地显示每个问题,并等待用户的回答,然后再显示下一个问题。如果是这样,那么我认为您实际上不需要使用循环。当用户回答当前问题时,您仅可以显示下一个问题。因此,您需要两个主要功能:一个显示一个问题,另一个在用户单击按钮时检查答案。

© www.soinside.com 2019 - 2024. All rights reserved.