Как проверить ответ пользователя нажатием кнопки javascript - PullRequest
0 голосов
/ 29 апреля 2020

В настоящее время я пытаюсь создать тест, прямо сейчас он отображает первый вопрос с 4 вариантами ответа после кнопки «Пуск». Я застрял в том, как получить ответ. Пользователь нажимает кнопку, проверьте, правильно ли она, и l oop на следующий вопрос. Я просто хочу дать пользователю один шанс на вопрос и двигаться дальше, независимо от того, правильно это или нет. Если они ответят неправильно, я уберу секунды из таймера. У меня есть вопросы, варианты ответов и правильные ответы в массивах.

<div class="card-body">
    <p id="header">
        You have 75 seconds to complete this asessment. 
        Every incorrect answer will cost you time.
        <br>
    </p>
    <button id="start-button" class="btn">Start</button>
    <div id="start-game" style="visibility: hidden">
        <button id="option0" data-index="0"></button><br>
        <button id="option1" data-index="1"></button><br>
        <button id="option2" data-index="2"></button><br>
        <button id="option3" data-index="3"></button><br>
    </div>
</div>

<script src="./script.js"></script>
var timerEl = document.getElementById("timer");
var start = document.getElementById("start-button");
var questionEl = document.getElementById("header");
var option0 = document.getElementById("option0");
var option1 = document.getElementById("option1");
var option2 = document.getElementById("option2");
var option3 = document.getElementById("option3");
var intials = document.getElementById("user-initials");
var buttonEl = document.getElementById("start-game");
var totalTime = 75;
var elapsedTime = 0;
var questionNum = 0;
var questions =["The condition in an if/else statement is enclosed with in _______",
                "Arrays in JavaScript can be used to store ______",
                "Commonly used data types do not include ______",
                "String values must be enclosed within _____ when being assigned to variables"];

var answers =[question1= ["Quotes","Curly brackets","Parentheses","Square brackets"],
              question2= ["Numbers and strings","Other arrays","Booleans","All of the above"],
              question3= ["Strings","Booleans","Alerts","Numbers"],
              question4= ["Commas","Curly brackets","quotes","parentheses"],
            ];             

var correctAnswers = [2,3,2,2];

start.addEventListener("click", function(){
    timer();
    displayQuestion();
    start.style.visibility = "hidden";
    buttonEl.style.visibility = "visible";
});



function timer(){

    var timerInterval = setInterval(function(){
        totalTime --;
        timerEl.textContent = totalTime;

        if(totalTime === 0){
        clearInterval(timerInterval);
        endQuiz();
        return;

    }
    }, 1000);
}

function newQuiz(){
    questionEl.textContent = (questions[0]);

};



function displayQuestion(){
for( var i = 0; i < questions.length ; i++){

    questionEl.textContent=(questions[i]);
    option0.textContent=(answers[i][0]);
    option1.textContent=(answers[i][1]);
    option2.textContent=(answers[i][2]);
    option3.textContent=(answers[i][3]);

    console.log(i);
    return;

}
}

1 Ответ

0 голосов
/ 29 апреля 2020

Привет, я постараюсь предоставить простое решение вашего вопроса без использования какого-либо сложного синтаксиса javascript, так что дальше ...

Сначала в вашем файле html обновите кнопку опции и добавьте свойство класса с именем clickOption (вы можете изменить имя класса, если хотите, но обязательно измените его и в других местах скрипта. js). Код показан ниже.

<button id="option0" class="clickOption"  data-index="0"></button><br>
<button id="option1" class="clickOption"  data-index="1"></button><br>
<button id="option2" class="clickOption"  data-index="2"></button><br>
<button id="option3" class="clickOption"  data-index="3"></button><br>

Теперь в вашем скрипте. js файл добавьте строку кода, показанную ниже. Я добавил встроенные комментарии для лучшего понимания

// get all elements with class clickoption i.e all option buttons
var elements = document.getElementsByClassName("clickOption");
//use the below array to track the selected answers
var selectedAnswers = [];


var clickOption = function() {
  /** Here I have reached the end of the test and,
      I am logging the array of user-selected options. 
      This array can be compared with correctAnswers array
      to determine whether the answer is correct or not  **/
 if(questionNum >= questions.length) {
    console.log(selectedAnswers);
    return;
 }
 /**Get the option value that was clicked.
    Here I am using parseInt because,
    the data-index attribute value will be in string format,
    and the correctAnswers array is in Number format so it is better,
    to keep the selectedAnswers array in Number format as it will faciliate
    easier data comparison**/  
 var selectedOption = parseInt(this.getAttribute('data-index'));
 // add the selected option to the selectedAnwsers Array
 selectedAnswers.push(selectedOption);
 /** here I am assuming that you are using the questionNum variable 
     to track the current question Number **/
 questionNum += 1;
  /** here I am again checking if I have reached the end of test and 
      thus log the answers
      Instead of logging the answer you can create a function 
      that compares the result and display it on screen **/
 if(questionNum >= questions.length) {
    console.log(selectedAnswers);
    return;
 }
 // update the next question text
 questionEl.textContent = questions[questionNum];
 // update next options
 displayQuestion(questionNum);
}

//loop through all the elements with class clickOption 
for (var i = 0; i < elements.length; i++) {
   elements[i].addEventListener('click', clickOption);
}

start.addEventListener("click", function() {
  timer();
  /** I have updated the displayQuestion call implementation
      so that the function is called with a parameter
      (here the parameter it is zero) **/
  displayQuestion(questionNum);
  start.style.visibility = "hidden";
  buttonEl.style.visibility = "visible";
});

/**Finally I have updated the display question method 
   so that it updates the option buttons based on the index parameter **/

 function displayQuestion(index){
  questionEl.textContent = questions[index];
  option0.textContent = answers[index][0];
  option1.textContent = answers[index][1];
  option2.textContent = answers[index][2];
  option3.textContent = answers[index][3];
 }

Надеюсь, что это решение поможет вам. Удачного кодирования!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...