简体   繁体   English

select有没有办法从JS中的一系列问题中一个接一个地提出问题

[英]Is there a way to select one question one after the other from an array of questions in JS

I'm building a quiz app using HTML, CSS and JS.我正在使用 HTML、CSS 和 JS 构建一个测验应用程序。 I have all the questions as objects in an array, but the issue is that I want to be able to display one question for the user to answer followed by the next question.我将所有问题作为数组中的对象,但问题是我希望能够显示一个问题供用户回答,然后是下一个问题。 So far, I have been unable to do that.到目前为止,我一直无法做到这一点。 I really really need help.我真的真的需要帮助。 I have been struggling for some days now.我已经挣扎了几天了。

var score = 0;
var maxQuestions = 0;

var questions = [
{ question: " javaScript is an....... language?",
    anwsers: [ "object-oriented", "object-based", "procedural", "none of the above"],
    correct: 1
    
},
{ question: "which of the following keywords is used a define variable in javaScript",
    anwsers: [ "var", "let", "both A and B", "none of the above"],
    correct: 2

  
}, 
{
    question: "which of the following methods is used to HTML elements using javaScript",
    anwsers: ["getElementsById", "getElementByClassName", "both A and B", "none of the above"] ,
    correct: 1
    
}
];

function showQuestion(questions){
    let ques = document.getElementById('questions');
    let qDiv = document.createElement('div');
    let p = document.createElement('p');
    p.textContent = questions[2]['question'];
    ques.appendChild(qDiv);
    qDiv.appendChild(p);

    let atl = document.querySelectorAll('.alts');
    atl.forEach(function(element, index){
        element.textContent = questions[2].anwsers[index];
        nextQuestion();

        element.addEventListener('click', function() {
            if(questions[2].correct === index) {
                console.log('correct answer');
            } else {
                console.log('wrong answer');
            }
        })
    })  
};

showQuestion(questions);
var btn = document.getElementById('btn');
btn.addEventListener('click', function() {
    console.log('clicked');
});

function nextQuestion() {
    if (maxQuestions !== questions.length) {
        
    }
}

I will offer some suggestions to help get you on the right track.我将提供一些建议来帮助您走上正轨。

First, your app will have to track some state. Specifically, you will need to know the current question the user is viewing and the sum of correct answers the user has chosen (the user's score ).首先,您的应用程序必须跟踪一些 state。具体来说,您需要知道用户正在查看的当前问题以及用户选择的正确答案的总和(用户的分数)。 I would make these items explicit by creating a state object:我会通过创建一个state object 来明确这些项目:

const state = {
  currentQuestionIndex: 0,
  score: 0
};

Next, we will modify our showQuestion function. Instead of passing to it the list of questions, we will pass the index of the question we wish to show.接下来,我们将修改我们的showQuestion function。我们将传递我们希望显示的问题的索引,而不是向它传递问题列表。 This will allow us later to show the next question when we increment the currentQuestionIndex in our state.这将允许我们稍后在我们增加currentQuestionIndex中的 currentQuestionIndex 时显示下一个问题。

I would also recommend dynamically generating the answer option elements based on the answers block of the current question.我还建议根据当前问题的answers块动态生成答案选项元素。 This way, different questions can have different numbers of potential answers.这样,不同的问题可以有不同数量的潜在答案。

The following is an example implementation of the function. I am including comments to help clarify:以下是 function 的示例实现。我包括评论以帮助澄清:

function showQuestion(questionIndex) {
  // Get the current question from the global `questions` array based on the given index.
  const question = questions[questionIndex];
  
  // I am using a naming convention of prefixing the variable names of DOM elements with "$". This is purely a stylistic choice.
  // I have given the element that will contain the question the id of "Question". Title-casing HTML IDs is another stylistic choice.
  const $question = document.getElementById("Question");
  const $div = document.createElement("div");
  const $p = document.createElement("p");

  // Clear the current HTML of the Question and Answers elements.
  $question.innerHTML = "";
  $answers.innerHTML = "";

  $question.appendChild($div);
  $div.appendChild($p);
  $p.textContent = question.question;

  // Loop through each potential answer for current question and
  // create a radio button. This assumes that the "Answers" element is a `<form>`
  question.answers.forEach((answer, answerIndex) => {
    const $input = document.createElement("input");
    const $label = document.createElement("label");

    $label.appendChild($input);
    $label.appendChild(document.createTextNode(answer));

    // Each radio input in the group gets the same name in order to restrict
    // the user to selecting only one.
    $input.name = `Question${questionIndex}`;
    $input.type = "radio";
    $input.value = answerIndex;

    $answers.append($label);
  });
}

Next we will permit the user to move to the next question when the button is clicked.接下来,我们将允许用户在单击按钮时转到下一个问题。

const $nextQuestion = document.getElementById("NextQuestion");
$nextQuestion.addEventListener("click", function () {
  // Increment the current question index in our state.
  state.currentQuestionIndex += 1;

  // If the new index is equal to the count of questions,
  // we have reached the last question and we will log the score.
  if (state.currentQuestionIndex === questions.length) {
    console.log(`Quiz complete: ${state.score} / ${questions.length}`);
  } else {
    // Otherwise, we will show the next question.
    showQuestion(state.currentQuestionIndex);
  }
});

For logging the correctness/incorrectness of the selected answer, instead of adding a listener to each radio input, we will attach a single listener to the Answers form that will listen for the change event:为了记录所选答案的正确性/不正确性,我们不会为每个无线电输入添加一个监听器,而是将一个监听器附加到将监听change事件的 Answers 表单:

const $answers = document.getElementById("Answers");
$answers.addEventListener("change", (event) => {
  // Get the current question based on the index in our state.
  const currentQuestion = questions[state.currentQuestionIndex];
  // Get the index of the answer the user selected from the value of the
  // radio button that was selected.
  const selectedAnswerIndex = Number(event.target.value);
  const correctAnswerIndex = currentQuestion.correct;
  const isCorrect = selectedAnswerIndex === correctAnswerIndex;
  
  // Increment state.score if the selected answer was the correct one.
  state.score += isCorrect ? 1 : 0;

  if (isCorrect) {
    console.log("correct answer");
  } else {
    console.log("wrong answer");
  }
});

Finally, initialize the quiz by rendering the first question:最后,通过呈现第一个问题来初始化测验:

showQuestion(0);

I hope these examples help to put you on the right track.我希望这些例子能帮助你走上正轨。 Here is a fiddle of the completed example for reference.是已完成示例的小提琴供参考。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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