简体   繁体   中英

Automize array object display from array database

I have an array containing 10 objects. Each contains a question string, a correctAnswer string, and an object with 4 answer strings:

const DB = [
{
  question: "some question",
  answers: ["a", "variety", "of", "choices"],
  correctAnswer: "variety"
}, ...

I have a function which captures the user's answer via radio button input, and saves it in a variable:

function feedbackPage(){
  $('.js-quizform-questions').on('click', '.js-button-next', function(event){
    event.preventDefault()
    let yourAnswer = getFeedback()
    $('.js-feedback-page').show().html(evalCorrectAnswer(DB))
  })
}

You see that evalCorrectAnswer reaches out to the above database for validation. At the moment i am only able to display and validate the hardcoded first answer, which is dynamically generated like this:

function generateQuestionElement(item) {
  return `
    <h2>${item[0].question}</h2>
    <form id='form'>
        <fieldset>
            <div class='css-answers'>
                <input id='answer1' type='radio' name='answer' required>
                <label for='answer1'>${item[0].answers[0]}</label>
            </div>
            <div class='css-answers'>
                <input id='answer2' type='radio' name='answer' required>
                <label for='answer2'>${item[0].answers[1]}</label>

I need a way to automatically choose the first question, to include its answers and display it via generateQuestionItem . Then I need to take that question (& its answers) out of the pool and display the next question once i click on a Next button on the eval page. I have a hard time implementing this feature in an object-oriented way.

Codepen

Construct a variable of

let questionNumber = 0

Then update the following line inside renderQuestion :

<label for='answer1'>${DB[questionNumber].answers[0]}</label>

Later create a function that updates questionNumber at each appropriate point.

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