简体   繁体   中英

display the question to div using innerhtml from array by clicking next button

I am making a flashcard which has bunch of question and I store them using array. I did random the questions but sometimes the questions is appear more than one. I'm about to show the question one by one by clicking the next button. Also, if the questions is finished, it should be stop to random the questions.

 var btnNext = document.getElementById("next"); words = [{ question: "HTML stands for", answer: "HyperText Markup Language" }, { question: "What is a href?", answer: "Link location attribute" }, { question: "What is extensions used to save HTML pages?", answer: ".html" } ] btnNext.addEventListener('click', function() { var tempWords = []; if (tempWords.length === 0) { for (var i = 0; i < words.length; i++) { tempWords.push(words[i]); } } let index = Math.floor(Math.random() * tempWords.length); document.getElementById("question").innerHTML=tempWords[index]?.question; });
 <div id="question"> <h3>Questions</h3> </div> <button id="next">Next</button>

There are 2 ways of doing what you want which i can think of

  • Shuffle the array and print questions one by one till the end of the array
  • Print random questions and removing them from the array

Shuffling the array

You can shuffle the array using differents methods and i've followed this stack overflow answer to do it which look the simplest

You can then remove each time the first question using the js shift method which remove the first element from an array and returns it

 var btnNext = document.getElementById("next"); words = [{ question: "HTML stands for", answer: "HyperText Markup Language" }, { question: "What is a href?", answer: "Link location attribute" }, { question: "What is extensions used to save HTML pages?", answer: ".html" } ] const randomWords = words.sort(() => Math.random() - 0.5); btnNext.addEventListener('click', function() { if (randomWords.length > 0) { const question = randomWords.shift() document.getElementById("question").innerHTML = question.question; } });
 <div id="question"> <h3>Questions</h3> </div> <button id="next">Next</button>

Printing random question

The second way works with the js splice function which remove elements from an array and return the removed elements (documentation here)

Printing question

To print question you can then access the function using the slice method:

const question = words.splice(index, 1)[0] // taking the first element because slice return an array

and then printing it using InnerHTML as you did

document.getElementById("question").innerHTML = question.question;

 var btnNext = document.getElementById("next"); words = [{ question: "HTML stands for", answer: "HyperText Markup Language" }, { question: "What is a href?", answer: "Link location attribute" }, { question: "What is extensions used to save HTML pages?", answer: ".html" } ] btnNext.addEventListener('click', function() { if (words.length > 0) { var tempWords = []; if (tempWords.length === 0) { for (var i = 0; i < words.length; i++) { tempWords.push(i); } } let index = Math.floor(Math.random() * tempWords.length); const question = words.splice(index, 1)[0] document.getElementById("question").innerHTML = question.question; } });
 <div id="question"> <h3>Questions</h3> </div> <button id="next">Next</button>

My idea is: Random the array at first. So your code (JS part) should be like this:

var btnNext = document.getElementById("next"),
tempwords = [{
    question: "HTML stands for",
    answer: "HyperText Markup Language"
  },
  {
    question: "What is a href?",
    answer: "Link location attribute"
  },
  {
    question: "What is extensions used to save HTML pages?",
    answer: ".html"
  }
],
words = [],
num = 0;
while (tempWords.length !== 0) {
  let index = Math.floor(Math.random() * tempWords.length);
  words.push(tempWords[index]);
  tempWords.splice(index, 1);
}
delete tempWords;

btnNext.addEventListener('click', function() {
  if (num < words.length) {
    let indexItems = words[num++];
  }
  // More code....
});

By putting track on index whether they are used previously or not.

  const btn = document.getElementById("next");
  var indexArray = [];
  btn.onclick = function getNewQuestion() {
    let tempWords = [
      "What is the capital of India?",
      'What is mean by "Lo siento"?',
      'What is mean by "mesa"?',
      'What is mean by "Para"?',
      "What is mean by 'Bonito'?",
    ];
    let index = getValidIndex(indexArray, tempWords.length);
    console.log(tempWords[index]);
  };

  // function to get valid non-repeative index
  function getValidIndex(indexArray, lengthOfTempWords) {
    let indexs = parseInt(Math.floor(Math.random() * lengthOfTempWords));
    let count = 0;
    for (let i = 0; i < indexArray.length; i++) {
      if (indexs == indexArray[i]) {
        count++;
      }
    }
    if (count > 0) {
      if (indexArray.length === lengthOfTempWords) {
        return -1;
      }
      return getValidIndex(indexArray, lengthOfTempWords);
    } else {
      indexArray.push(indexs);
      return indexs;
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM