Почему моя кнопка HTML не регистрирует клик? - PullRequest
0 голосов
/ 09 октября 2019

Я работаю над отправкой форм и отображением контента на основе выбранного ответа. Сейчас я просто пытаюсь заставить кнопки работать, чтобы они могли переходить от одного вопроса к отображению с правильным ответом и затем переходить к следующему вопросу. index.js

function startQuiz() {
    $('#startButton').click(function(event){
        console.log("Keep Going");
        renderQuestion();
    }
    );
}
let questionNumber= 0

function renderQuestion() {
    console.log("hello");
    let questions = STORE.questions[questionNumber];
    const questionTemplate = $( `
    <div class="container" align="center">
        ${questions.image}
          <p>${questions.questionText}<br></p>
          <form method="post" onsubmit="return nextQuestion()">
              <input type="radio" name="choice">${questions.responses[0]}<br>
              <input type="radio" name="choice">${questions.responses[1]}<br>
              <input type="radio" name="choice">${questions.responses[2]}<br>
              <input type="radio" name="choice">${questions.responses[3]}<br>
              <button input type="submit" id="choose" value="submit">Submit</button>
            </form>
      </div>`);
      $("main").html(questionTemplate);
}

function checkAnswer() {
$("main").on("click","#choose",function(event){
    let questions = STORE.questions[questionNumber];
    event.preventDefault();
    console.log("clicked");
    const correctResponse = $(`
    <div class="container" align="center">
    ${questions.image}
    <h4>${questions.answer}</h4>
    <p>Correct!<p>
    <button input type="submit id="next" value="submit">Next</button>
    </div>`);
    $("main").html(correctResponse);
})
}

function nextQuestion(){
$("main").on("click","#next",function(event){
    event.preventDefault();
    console.log("Don't turn back");
    questionNumber= questionNumber +1;
    renderQuestion();
})}

$(checkAnswer)
$(startQuiz)

Я создал console.log(), чтобы я мог видеть, когда кнопка нажата, но она не появляется. С другой стороны, он не обновляет страницу, просто кажется, что он ничего не делает.

index.html


<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Herbal Medicine: Adaptogens</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
  <link rel="questions" href="store.html">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="index.js"></script>
  <script src="store.js"></script>
</head>

<body>
  <h1>Herbal Medicine: Adaptogens</h1>
  <main>
    <div class="container" class="firstLetter">
      <p>Adaptogens are a category of healing herbs that have a number of beneficial qualities for the human body. They
        are characterized by their ability to perform well with other medications and supplements, they can build up in
        the system without negative effects, and they help the body adapt to stress on many levels. <br> 
        Stress can be emotional, physical and mental and the various adaptogens tend to apply their healing qualities to those areas
        of the body that most need support.<br>
        Herbal medicine has been cataloged throughout the ages, with physical records uncovered as early as 1500 BCE.
        Most prescription medications have been derived from plants, and their latin or botanical names will indicate
        such.<br>
        Test your knowledge and learn a thing or two about healing herbs!<br>
      </p>
      <button id="startButton">Start</button>
      <br> <h12>The statements in this quiz are not intended to diagnose or treat any conditions. When in doubt ask a pro!</h12>
    </div>
      </main>

</body>

</html>

store.js

const STORE = {
    questions: [ {
        image: `<div class="image"> <img src="nettles.svg", alt="mystery plant illustration"> </div>`,
            questionText: "Which plant provides the most minerals and nutrients.",
            responses: [
                "Licorice <i>Glycyrrhiza glabra</i>",
                "Jiagulon <i>Gynostemma pentaphyllum</i>",
                "Lemon Balm <i>Melissa Officianlis</i>",
                "Nettles <i>Urtica dioica</i>"
            ],
            answer: "Nettles <i>Urtica dioica</i>"
        },
        {
            questionText: "Which Plant is known for lowering  high cholesterol, high blood pressure, and improving heart function as well as improving memory, and preventing hair loss?",
            responses: [
                "Jiagulon <i>Gynostemma pentaphyllum</i>",
                "Licorice <i>Glycyrrhiza glabra</i>",
                "Nettles <i>Urtica dioica</i>",
                "Lemon Balm <i>Melissa Officianlis</i>"
            ],
            answer: "Jiagulon <i>Gynostemma pentaphyllum</i>"
        }
]
}

Ответы [ 2 ]

0 голосов
/ 10 октября 2019

У вас есть несколько мелких проблем, включая опечатку:

  1. кнопка не может иметь атрибут "input"
  2. В checkAnswer () у вас есть закрытое "после submit: type ="submit id =" next "

Основная проблема заключается в том, что у вас есть кнопка eventListener на кнопке #choose, а также функция onsubmit в форме. Исправьте эти проблемы выше, удалите onsubmit и добавьте nextQuestion () в конец checkAnswer (), и оно должно работать нормально. Остальная часть вашего кода в порядке.

0 голосов
/ 10 октября 2019

В index.js попробуйте это,

function checkAnswer() {
$("main").on("click","#choose",function(event){
    let questions = STORE.questions[questionNumber];
    event.preventDefault();
    console.log("clicked");
    const correctResponse = $(`
    <div class="container" align="center">
        ${questions.image}
    <h4>${questions.answer}</h4>
    <p>Correct!<p>
    <button input type="submit" id="next" value="submit">Next</button>
    </div>`);
    $("main").html(correctResponse);
    // for registering #next id event
    nextQuestion();
})

}

// Объяснение:

функция nextQuestion() регистрирует ваше событие #next click, в DOM идентификатор #next будет присутствовать после $ ("main"). html (correctResponse);линия. поэтому nextQuestion () должен вызываться, когда #next id будет успешно помещен в DOM.

...