Я изучаю JavaScript и пишу программу викторины как часть процесса обучения.

<!DOCTYPE html> 
<html>          
        <head>  
                <meta charset="UTF-8">                                              
        </head> 
        <body>  
                <form type="submit" onsubmit = "populateQuestion()">                
                        <h2 id="question">Question goes here</h2>                   
                        <input name = "option" type="radio" value="A"><span id = "choiceA">First option here</span><br/>
                        <input name = "option" type="radio" value="B"><span id = "choiceB">Second option here</span><br/>
                        <input name = "option" type="radio" value="C"><span id = "choiceC">Third option here</span><br/>
                        <input name = "option" type="radio" value="D"><span id = "choiceD">Fourth option here</span><br/>
                        <button type = "submit">Submit</button>                     
                </form>                       
        </body>                                                                     

<script>
var question = document.getElementById("question");
var choiceA = document.getElementById("choiceA");
var choiceB = document.getElementById("choiceB");
var choiceC = document.getElementById("choiceC");
var choiceD = document.getElementById("choiceD");

var quesIndex = 0;
var defQuestions = [
        {
                question : "Q01?",
                choiceA : "A1",
                choiceB : "B1",
                choiceC : "C1",
                choiceD : "D1",
                answer : "A"
        },
        {
                question : "Q02?",
                choiceA : "A2",
                choiceB : "B2",
                choiceC : "C2",
                choiceD : "D2",
                answer : "A"

        },
        {
                question : "Q03?",
                choiceA : "A3",
                choiceB : "B3",
                choiceC : "C3",
                choiceD : "D3",
                answer : "B"

        },
        {
                question : "Q04?",
                choiceA : "A4",
                choiceB : "B4",
                choiceC : "C4",
                choiceD : "D4",
                answer : "B"

        }
];

function renderQuestion() {
        question.innerHTML = defQuestions[quesIndex].question;
        choiceA.innerHTML = defQuestions[quesIndex].choiceA;
        choiceB.innerHTML = defQuestions[quesIndex].choiceB;
        choiceC.innerHTML = defQuestions[quesIndex].choiceC;
        choiceD.innerHTML = defQuestions[quesIndex].choiceD;
}

function populateQuestion() {
        console.log(quesIndex);
        renderQuestion();
        quesIndex += 1;
}

populateQuestion();
</script>
</html> 

Когда я загружаю страницу, populateQuestion() выполняет и загружает вопрос и параметры по умолчанию (первый элемент массива defQuestions). Эта часть работает нормально.

Image

Когда я нажимаю кнопку Submit, следующий вопрос должен быть загружен. Но следующий вопрос не загружается.

console.log(quesIndex); печатает только 0, а затем окно консоли очищает журналы.

Что-то не так в реализации?

0
Nayab Basha Sayed 27 Окт 2019 в 18:39

3 ответа

Лучший ответ

Я не уверен, как вы собираетесь обрабатывать отправку формы, но ваша текущая реализация отправит форму, что приведет к перезагрузке страницы и сбросу сценария.

Вы должны добавить прослушиватель событий для захвата для события отправки формы и обработать его самостоятельно (я думаю, вы будете хранить ответы пользователей в массиве)

var question = document.getElementById("question");
var choiceA = document.getElementById("choiceA");
var choiceB = document.getElementById("choiceB");
var choiceC = document.getElementById("choiceC");
var choiceD = document.getElementById("choiceD");

var quesIndex = 0;
var defQuestions = [{
    question: "Q01?",
    choiceA: "A1",
    choiceB: "B1",
    choiceC: "C1",
    choiceD: "D1",
    answer: "A"
  },
  {
    question: "Q02?",
    choiceA: "A2",
    choiceB: "B2",
    choiceC: "C2",
    choiceD: "D2",
    answer: "A"

  },
  {
    question: "Q03?",
    choiceA: "A3",
    choiceB: "B3",
    choiceC: "C3",
    choiceD: "D3",
    answer: "B"

  },
  {
    question: "Q04?",
    choiceA: "A4",
    choiceB: "B4",
    choiceC: "C4",
    choiceD: "D4",
    answer: "B"

  }
];


var questionnaire = document.getElementById("questionnaire");

function renderQuestion() {
  question.innerHTML = defQuestions[quesIndex].question;
  choiceA.innerHTML = defQuestions[quesIndex].choiceA;
  choiceB.innerHTML = defQuestions[quesIndex].choiceB;
  choiceC.innerHTML = defQuestions[quesIndex].choiceC;
  choiceD.innerHTML = defQuestions[quesIndex].choiceD;
}

function populateQuestion() {
  console.log(quesIndex);
  renderQuestion();
  quesIndex += 1;
}

function onsubmit(e) {
  e.preventDefault(); //prevent form from actually posting
  var a = questionnaire.querySelector('input[name = option]:checked'); 
  
  console.clear();
  console.log("Q:",quesIndex,"Answer:",a.value);
  a.checked=false;//deselect it ready for new question
  populateQuestion();
}

questionnaire.addEventListener('submit', onsubmit, false);


populateQuestion();
form {
    margin-bottom:100px;/* just some space for the console log in the snippet*/
}
<form id="questionnaire" type="submit">
  <h2 id="question">Question goes here</h2>
  <input name="option" type="radio" value="A"><span id="choiceA">First option here</span><br/>
  <input name="option" type="radio" value="B"><span id="choiceB">Second option here</span><br/>
  <input name="option" type="radio" value="C"><span id="choiceC">Third option here</span><br/>
  <input name="option" type="radio" value="D" required><span id="choiceD">Fourth option here</span><br/>
  <button type="submit">Submit</button>
</form>
2
Moob 27 Окт 2019 в 16:15

Вот пересмотренный код, он работает в jsfiddle.net. Таким образом, в основном вам нужно обновить QuesIndex, прежде чем рендерить новый вопрос.

    <!DOCTYPE html> 
<html>          
        <head>  
                <meta charset="UTF-8">                                              
        </head> 
        <body>  
                <form type="submit" onsubmit = "populateQuestion()">                
                        <h2 id="question">Question goes here</h2>                   
                        <input name = "option" type="radio" value="A"><span id = "choiceA">First option here</span><br/>
                        <input name = "option" type="radio" value="B"><span id = "choiceB">Second option here</span><br/>
                        <input name = "option" type="radio" value="C"><span id = "choiceC">Third option here</span><br/>
                        <input name = "option" type="radio" value="D"><span id = "choiceD">Fourth option here</span><br/>
                        <button type = "submit">Submit</button>                     
                </form>                       
        </body>                                                                     

<script>
var question = document.getElementById("question");
var choiceA = document.getElementById("choiceA");
var choiceB = document.getElementById("choiceB");
var choiceC = document.getElementById("choiceC");
var choiceD = document.getElementById("choiceD");

var quesIndex = 0;
var defQuestions = [
        {
                question : "Q01?",
                choiceA : "A1",
                choiceB : "B1",
                choiceC : "C1",
                choiceD : "D1",
                answer : "A"
        },
        {
                question : "Q02?",
                choiceA : "A2",
                choiceB : "B2",
                choiceC : "C2",
                choiceD : "D2",
                answer : "A"

        },
        {
                question : "Q03?",
                choiceA : "A3",
                choiceB : "B3",
                choiceC : "C3",
                choiceD : "D3",
                answer : "B"

        },
        {
                question : "Q04?",
                choiceA : "A4",
                choiceB : "B4",
                choiceC : "C4",
                choiceD : "D4",
                answer : "B"

        }
];

function renderQuestion() {
        question.innerHTML = defQuestions[quesIndex].question;
        choiceA.innerHTML = defQuestions[quesIndex].choiceA;
        choiceB.innerHTML = defQuestions[quesIndex].choiceB;
        choiceC.innerHTML = defQuestions[quesIndex].choiceC;
        choiceD.innerHTML = defQuestions[quesIndex].choiceD;
}

function populateQuestion() {
        console.log(quesIndex);
        quesIndex += 1;
        renderQuestion();
}

populateQuestion();
</script>
</html> 
-1
Protocleus EDM 28 Окт 2019 в 03:16

Попробуйте присоединить к своей форме идентификатор и прослушиватель событий при отправке в форме, чтобы предотвратить поведение формы по умолчанию, не позволяющее вашей форме перезагружать страницу и выполнять там свою логику.

1
Ali 27 Окт 2019 в 16:06