Как я могу перестать повторять свой код в такой ситуации? - PullRequest
0 голосов
/ 06 мая 2020

Я пытаюсь создать простую игру с API викторин, и вот мой html код:

<body>
    <div class="container-fluid row">
        <div class="col question">
            <h5>Question</h5>
            <h2 class="text-primary">0/5</h2>
        </div>
        <div class="col score text-right">
            <h5>Score</h5>
            <h2 class="text-primary">0</h2>
        </div>
    </div>
    <div class="container bg-light">
        <h1 class="display-3" id="questions"> What is the answer to this question? </h1>
        <div class="info-question">
            <div class="choice" id="1"></div>

            <div class="choice" id="2"></div>

            <div class="choice" id="3"></div>

            <div class="choice" id="4"></div>

        </div>
    </div>

    <script src="/trivia/trivia.js"></script>
</body>

Мой Javascript код:

let question_one = document.getElementById('1')
let question_two = document.getElementById('2')
let question_three = document.getElementById('3')
let question_four = document.getElementById('4')
fetch(`https://opentdb.com/api.php?amount=5&category=9&difficulty=easy&type=multiple`)
    .then((response) => response.json())
    .then(({
        results,
    }) => {
        question_one.textContent = `Question 1: ${results[0].question}`
        question_two.textContent = `Question 2: ${results[1].question}`
        question_three.textContent = `Question 3: ${results[2].question}`
        question_four.textContent = `Question 4: ${results[3].question}`

    });

Я пытаюсь для l oop через вопросы результата, но не знаю, как и с чего начать? Я ценю каждый ответ!

Ответы [ 4 ]

1 голос
/ 06 мая 2020

Вам необходимо создать функцию, работающую как шаблон. Вы можете определить свою структуру html в своем файле js.

function getQuestionHTML(question, index){
  return `<div class="choice" id="${index}">${question}</div>`
}

const questionsInfoEl = docuement.querySelector('info-question');
fetch(`https://opentdb.com/api.php?amount=5&category=9&difficulty=easy&type=multiple`)
    .then((response) => response.json())
    .then(({
        results,
    }) => {
      const questionHTMLList = results.map((data, index) => getQuestionHTML(data.question, index));
      questionsInfoEl.insertAdjacentHTML('afterend', questionHTMLList.join(''));
    });
1 голос
/ 06 мая 2020

Если у вас есть результаты динамического c, вы можете предпочесть не инициализировать свой div, содержащий результаты, а просто контейнер:

const containerEl = document.getElementById('choices-container');

fetch(`https://opentdb.com/api.php?amount=5&category=9&difficulty=easy&type=multiple`)
    .then((response) => response.json())
    .then(({
        results,
    }) => {
        results.map((result, idx) => {
          const node = document.createElement('div')
          node.textContent = `Question ${idx + 1}: ${result.question}`
          node.classList.add('choice')
          containerEl.append(node)
        })
    });

Также обновите html:

 <div class="info-question" id="choices-container">
   <!-- Remove divs, just initialize container -->
 </div>
1 голос
/ 06 мая 2020

вы можете сделать что-то вроде этого:

<div class="info-question">
        <div class="choice ques" id="1"></div>

        <div class="choice ques" id="2"></div>

        <div class="choice ques" id="3"></div>

        <div class="choice ques" id="4"></div>

    </div>

затем в js:

let questions = document.querySelectorAll('.ques');
fetch(`https://opentdb.com/api.php?amount=5&category=9&difficulty=easy&type=multiple`)
    .then((response) => response.json())
    .then(({
        results,
    }) => {
        questions.map((ques, I) => {
            ques.textContent = `Question ${i+1}: ${results[i].question}`
        }

    });

убедитесь, что у вас должен быть уникальный класс, который используется только в вопросах, в данном случае ques

0 голосов
/ 06 мая 2020

Ваши файлы HTML и js после изменений будут выглядеть следующим образом.

<body>
  <div class="container-fluid row">
     <div class="col question">
         <h5>Question</h5>
         <h2 class="text-primary">0/5</h2>
     </div>
     <div class="col score text-right">
         <h5>Score</h5>
         <h2 class="text-primary">0</h2>
    </div>
  </div>
  <div class="container bg-light">
     <h1 class="display-3" id="questions"> What is the answer to this question? </h1>
     <div class="info-question"></div>
 </div>
 <script src="/trivia/trivia.js"></script>

let questions = document.querySelector('.info-question');
fetch(`https://opentdb.com/api.php?amount=5&category=9&difficulty=easy&type=multiple`)
    .then((response) => response.json())
    .then(({results}) => {
        let fragment = document.createDocumentFragment();
        results.forEach((data,index)=>{
            let div = document.createElement('div');
           div.textContent = `Question ${index+1}: ${data.question}`;
           div.className = 'choice';
           div.id = index;
           fragment.appendChild(div);
        })
        questions.appendChild(fragment);

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