He creado una serie de objetos por los que necesito que pase mi bucle for . Sin embargo, cuando ejecuto este código, solo veo la primera pregunta y sus respuestas. ¿Qué estoy haciendo mal? ¡Gracias de antemano!
// An array of objects containing questions, answers, and the correct answers. const questionArray = [ { Q: "TestingQ1", A: [ "Testing2", "Testing3", "Testing4", "Testing5" ], Correct: "Testing2" }, { Q: "TestingQ2", A: [ "Testing2-2", "Testing3-2", "Testing4-2", "Testing5-2" ], Correct: "Testing3-2" } ]; // Set to zero to target the first index in an array of objects. let questionIndex = 0; // showQuestions is equal to elements with the "show-questions" class. Here, a section. let showQuestions = document.querySelector(".show-questions"); // showAnswers is equal to the elements in the "show-answers" class. Here, a section. let showAnswers = document.querySelector(".show-answers"); // results is equal to the "results" id. Here, a span. let results = document.querySelector("#results"); // Create a function that displays questions function displayQuestions() { showQuestions.textContent = questionArray[questionIndex].Q; console.log(showAnswers); for (let i = 0; i < questionArray[questionIndex].A.length; i++) { let answerButton = document.createElement("button"); answerButton.textContent = questionArray[questionIndex].A[i]; // Define the function here to check the answers answerButton.onclick = function checkAnswers() { // If the submission is equal to Correct... if (answerButton.innerText === questionArray[questionIndex].Correct) { // ...show this confirmation message. results.textContent = "Right on, popcorn! That's correct."; console.log(checkAnswers); // If the submission is not equal to Correct... } else { // ...show this error message and... results.textContent = "Sorry, no such luck. Try again!"; // ...deduct 10 seconds from the clock. secondsLeft -= 10; } }; showAnswers.appendChild(answerButton); }No está viendo un bucle a través de sus otras preguntas porque su bucle for está vinculado a su primer objeto.
for (let i = 0; i < questionArray[questionIndex].A.length; i++)Esto significa que su ciclo for debe terminar con la longitud de las respuestas en su primer objeto. Después de esto, su bucle debería cerrarse. Para que su bucle pase por todos los objetos, puede hacerlo de dos maneras según mi conocimiento: Mi forma preferida
Un ciclo forEach en su matriz y luego el ciclo for para cada objeto como lo ha hecho.
O
Probablemente pueda crear un primer forLoop para sus objetos de matriz antes del forLoop interno que tiene.
De esta manera, hay un bucle que pasa por sus preguntas y un bucle para encontrar su respuesta.
Espero que esto te guíe sobre cómo hacerlo.
Debe recorrer todos los elementos de esa matriz. Solo está mostrando la primera pregunta.
Lea más sobre el método forEach en matrices aquí: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
Deberías tener algo como:
function displayQuestions() { questionArray.forEach(function (question, index) { // Create a new div for each question. let questionDiv = document.createElement("div"); // Add a class to the new div. questionDiv.classList.add("question"); // Add the question to the new div. questionDiv.innerHTML = question.Q; // Append the new div to the showQuestions section. showQuestions.appendChild(questionDiv); // Create a new div for each answer. let answerDiv = document.createElement("div"); // Add a class to the new div. answerDiv.classList.add("answer"); // Add the answers to the new div. question.A.forEach(function (answer) { answerDiv.innerHTML += `<button class="answer-button">${answer}</button>`; }); // Append the new div to the showQuestions section. showQuestions.appendChild(answerDiv); });Verifique mi git repo en la misma aplicación y verifique el archivo quiz.js
También adjunté el código quiz.js aquí
enlace de repositorio: https://github.com/abdulhaseeb036/quiz-website
código quiz.js:
var questions = [ { id : 1, question : "Who is the owner of this Quiz app", answer : "Haseeb Alam Rafiq", option : [ "Haseeb Alam Rafiq", "Muhammad Wasi", "Mark zinger Burger", "None of these" ] }, { id : 2, question : "When was MR HASEEB ALAM born?", answer : "12-dec-2000", option : [ "13-aug-2000", "12-may-1999", "1-march-2001", "12-dec-2000" ] }, { id : 3, question : "Which university MR HASEEB ALAM RAFIQ complete Becholars degree?", answer : "Lumber 1 university", option : [ "Baharia university ", "Lumber 1 university", "IBM university", "DHA suffah university" ] }, ] // var welcome = document.getElementById(location.href="../index.html" ,"first-ip"); // console.log(welcome.value); // counter var counter = 0; var userPoints = 0; function nextq() { var userAns = document.querySelector("li.option.active").innerHTML; if (userAns == questions[counter].answer){ userPoints = userPoints + 5; sessionStorage.setItem("points" ,userPoints); } if (counter == questions.length -1) { location.href = "../end.html"; return; } console.log(userPoints); counter++; show(counter); } // on every onload mean refresh this function calls and in this function // show(counter) function calls window.onload = function() { show(counter); //here counter value 0 means first q render on refresh page. } // this function render onclick new question with options function show(counter) { var question = document.getElementById("questions"); question.innerHTML=` <h2>Q${counter +1}. ${questions[counter].question}</h2> <ul> <li class="option">${questions[counter].option[0]}</li> <li class="option">${questions[counter].option[1]}</li> <li class="option">${questions[counter].option[2]}</li> <li class="option">${questions[counter].option[3]}</li> </ul> `; toggleActive(); } function toggleActive() { let option1 = document.querySelectorAll("li.option"); for(let i = 0; i< option1.length; i++){ option1[i].onclick =function() { for(let j = 0; j< option1.length; j++){ if(option1[j].classList.contains("active")){ option1[j].classList.remove("active"); } option1[i].classList.add("active"); } } } }