Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

201
Views
¿Cómo puedo seleccionar todas las etiquetas de clase y establecerlas en etiquetas de objetos en menos líneas?

 const btn_start = document.getElementById("start"); let container = document.getElementById("container"); let questionTag = document.getElementById("question"); let answerTag = document.getElementsByClassName("answer"); btn_start.addEventListener("click", startQuiz); const myQuestions = [ { question: "What's 2+2?", answers: [ { text: "4", correct: true }, { text: "2", correct: false }, { text: "10", correct: false }, { text: "1", correct: false }, ], }, ]; function startQuiz() { container.style.visibility = "visible"; btn_start.style.visibility = "hidden"; showQuestion(); } function showQuestion() { questionTag.innerText = myQuestions[0].question; answerTag[0].innerHTML = myQuestions[0].answers[0].text answerTag[1].innerHTML = myQuestions[0].answers[1].text answerTag[2].innerHTML = myQuestions[0].answers[2].text answerTag[3].innerHTML = myQuestions[0].answers[3].text }
 .answers button{ display: block; width: 100%; height: 45px; margin-bottom: 5px; background-color: white; border: 1.5px solid lightblue; cursor: pointer; border-radius: 5px; }
 <button id="start" type="button">Start quiz</button> <div id="container"> <h2>Quiz</h2> </div> <h3 id="question"></h3> <div class="answers"> <button id="answer1" class="answer"></button> <button id="answer2" class="answer"></button> <button id="answer3" class="answer"></button> <button id="answer4" class="answer"></button> </div>

En lugar de tener que asignar cada etiqueta de respuesta a una de las respuestas de mi objeto. ¿Cómo se puede hacer al azar? y asignado a una etiqueta de respuesta aleatoria. ¿Se puede usar math.random en objetos y luego en mis botones para asignar aleatoriamente?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Mire el problema en una vista más general. Pregúntese: "¿Qué se supone que debe hacer este código en su nivel más básico?"

yo responderia...

Tome una pregunta y sus respuestas asociadas, luego muestre esa pregunta y muestre sus respuestas en orden aleatorio.

Entonces su HTML tiene espacios para el texto de la pregunta y cuatro respuestas. También deberíamos mirarlos en general. answer1 es solo un espacio para contener una de las cuatro respuestas disponibles de nuestra pregunta. No tiene que mostrar solo la Respuesta n.º 1 para la Pregunta n.º 1.

 // Shuffling an array is a little harder than it seems at first. I'm // importing the Lodash library here because it provides a function for // randomizing an array. const _ = require('lodash'); // This function takes an object parameter that matches the shape of // the question-and-answers objects in your original code. // { // question: string; // answers: { text: string; correct: boolean; }[]; // } function showQuestion(questionAndAnswers) { // Randomly order the answers. const shuffledAnswers = _.shuffle(questionAndAnswers.answers); // Set the question tag's text to the question text provided. questionTag.innerText = questionAndAnswers.question; // For each of the answers that we shuffled, populate the answer // tag of the same index with the answer's text. // For answers ['Car', 'Bike', 'Train', 'Plane'], // 'Car' goes into Tag[0] // 'Bike' goes into Tag[1] // ...etc shuffledAnswers.forEach((answer, idx) => { answerTag[idx] = answer.text; }); }

Ahora, con esta función de propósito general que toma algún objeto que contiene su pregunta y las respuestas disponibles (como ya tiene), podemos mostrar las preguntas con facilidad.

 function startQuiz() { // Your original code omitted... // Extract the 0th element from the list of questions, then display it. showQuestion( myQuestions[0] ); }

Cuando sea el momento de pasar a la siguiente pregunta...

 let currentQuestion = 0; btn_next_question.addEventListener("click", showNextQuestion); function showNextQuestion() { currentQuestion = currentQuestion + 1; showQuestion( myQuestions[currentQuestion] ); }

Eche otro vistazo a la respuesta a la pregunta planteada al principio. La función showQuestion() cumple con esta descripción general del problema. Para cualquier par de preguntas y sus respuestas, showQuestion() completará los elementos HTML necesarios para mostrar la pregunta y mostrar sus respuestas en orden aleatorio. La lógica de su código original se ha reciclado, pero ahora es más general y funciona con un valor arbitrario en lugar de valores fijos.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!