Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

202
Visualizações
¿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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda