首页 > 解决方案 > 将对象值传播到输入框中

问题描述

我正在尝试编写一个 javascript 测验应用程序。Atm 我坚持将可能的答案放入四个盒子之一。所以只是为了确保你理解我想要成为什么:我从一个 API 获取问题。答案收集在一个对象中,我想将答案随机放入我的 4 个选项框中。我已经尝试了一些事情,但此刻我不知道发生了什么......这是我的代码:

<body>
    <div id="questioncontainer" class="main-container">
        <div id="progression"><div id="progressfull"></div></div>
        <div id="header">
                <h2 id="vraagnummer">Vraag #</h2>
                <div><h2 id="timer"></h2></div>
        </div>
        <h2 id="vraaginput">In welke film wordt er kritiek geuit op de socio-economische situatie in Tsjechië in de late jaren 70?</h2>
        <div id="antwoordcontainer">
                <li id="Qst1"><p class="choice-text" data-number="1">Choice 1</p></li>
                <li id="Qst2"><p class="choice-text" data-number="2">Choice 2</p></li>
                <li id="Qst3"><p class="choice-text" data-number="3">Choice 3</p></li>
                <li id="Qst4"><p class="choice-text" data-number="4">Choice 4</p></li>
                <li id="Qst5"><p class="choice-text" data-number="5">Choice 5</p></li>
                <li id="Qst6"><p class="choice-text" data-number="6">Choice 6</p></li>
        </div>

        <button id="Quitgame">Ik stop ermee ze</button>    
    </div>

</body>

这是更少的代码,其中包含最重要的内容。

fetch(myUrl)
    .then((res) => {
        return res.json();
    })
    .then((loadedQuestions) => {
        for (let i = 0; i < MAX_VRAGEN; i++) {
            vragen = loadedQuestions;
            vragenTeller++;
            mijnVraag.innerHTML = vragen[i].question;
            console.log(vragen[i]);
            choices.forEach((choice) => {
                choice.innerHTML = vragen[i].answers.object;
            });


        };
        startGame();
    })
    .catch(err => {
        console.error(err);
    });

标签: javascript

解决方案


这是一个工作示例。我认为最好在 HTML 中创建选项,而不是硬编码七个答案并隐藏不包含可选答案的答案。这使代码稍长,但更具动态性。

问题是答案以对象的形式出现,所以我需要使用Object.keys(question.answers),所以我有一个最大值来随机化。然后我只是随机化了一个位置,并在 while 循环中添加答案的同时删除了该位置。

我希望代码是不言自明的。我试图尽可能地重构代码。

哦,我当时只预加载一个问题,而不是像原始代码中那样获取 15 个问题。

const quizURL = 'https://quizapi.io/api/v1/questions?apiKey=kAFKilHLeEcfLkGE2H0Ia9uTIp1rYHDTIYIHs9qf&limit=1';
var progression = 0;
var questionObj = {};
const questionEl = document.getElementById('vraaginput');
const answerContainerEl = document.getElementById('antwoordcontainer');
const currentQuestionEl = document.getElementById('vraagnummer');

document.getElementById('startGame').addEventListener('click', startGame);
document.getElementById('nextQuestion').addEventListener('click', nextQuestion);

function fetchQuestion() {
  fetch(quizURL)
    .then((res) => {
      return res.json();
    })
    .then((loadedQuestions) => {
      questionObj = loadedQuestions.pop();
    })
    .catch(err => {
      console.error(err);
    });
}

function startGame() {
  document.getElementById('startGame').setAttribute('hidden', true);
  document.getElementById('questionContainer').removeAttribute('hidden');
  nextQuestion();
}

function nextQuestion() {
  displayQuestion(questionObj);
  fetchQuestion();
}

function displayQuestion(question) {
  progression++;
  currentQuestionEl.innerHTML = `Vraag #${progression}`;
  questionEl.innerText = question.question;
  randomizeAnswerOptions(question.answers, question.correct_answers);
}

 // Here is the randomization for the options.
 // I created the radio buttons in javascript.

function randomizeAnswerOptions(options, answers) {
  const divContainer = document.createElement('div');
  var randomIndex, answerText = '', answerIndex = 0, isExistingAnswer = false, isCorrectAnswer = false;
  var optionsKeys = Object.keys(options);

  while(optionsKeys.length) {
    randomIndex = randomize(optionsKeys.length);
    randomIndex = optionsKeys.splice(randomIndex, 1)[0];
    answerText = options[randomIndex];
    isExistingAnswer = answerText != null;
   
    if (isExistingAnswer) {
      isCorrectAnswer = answers[randomIndex + '_correct']
      answerIndex++;
      divContainer.appendChild(createAnswerRow(answerText, isCorrectAnswer, 'answerInput' + answerIndex));
    }
  }

  answerContainerEl.innerHTML = '';
  answerContainerEl.appendChild(divContainer);
}

function createAnswerRow(answerText, isCorrectAnswer, inputId) {
  let answerRow = document.createElement('div');
  let bullet = document.createElement('input');
  let label = document.createElement('label');

  bullet.setAttribute('type', 'radio');
  bullet.setAttribute('name', 'answer');
  bullet.setAttribute('id', inputId);
  bullet.setAttribute('data-answer', isCorrectAnswer);

  label.setAttribute('for', inputId);
  label.innerText = answerText;
  
  answerRow.appendChild(bullet);
  answerRow.appendChild(label);
  
  return answerRow;
}

function randomize(max, min) {
  return Math.floor(Math.random() * max + (min || 0));
}

fetchQuestion();
#antwoordcontainer > div > div {
  margin: 0.25rem;
}

label, input[type="radio"] {
  cursor: pointer;
}

label {
  padding: 0.25rem;
}

input[type="radio"]:checked ~ label {
  background: pink;
}

input[type="radio"][data-answer="true"]:checked ~ label {
  background: lightgreen;
}
<button id="startGame">Start Game</button>

<div id="questionContainer" class="main-container" hidden>
  <div id="progression">
    <div id="progressfull"></div>
  </div>
  <div id="header">
    <h2 id="vraagnummer">Vraag #</h2>
    <div>
      <h2 id="timer"></h2>
    </div>
  </div>
  <h2 id="vraaginput"></h2>
  
  <div id="antwoordcontainer"><!--ANSWERS--></div>

  <button id="nextQuestion">Next Question</button>
  <!--<button id="Quitgame">Ik stop ermee ze</button>-->
</div>


推荐阅读