首页 > 解决方案 > 测验应用程序 - 表单中带有提交按钮的 jquery 问题

问题描述

function submitAnswer() {
$('.textBox').on("click",".submitButton",function (event) {    

    event.preventDefault();    
    $('.js-responseBox').show();   
    let selected = $('input:checked');    
    let answer = selected.val();   
    let correct = `${store[questionNumber].correctAnswer}`;    
    if (answer === correct)    
    {    
      $('.js-responseBox').html(    
      `<h3>Your answer is correct!</h3>   
      <p>Good Job</p>    
      <button type="button" class="nextButton button">Next</button>`    
      );    
      updateScore();    
    }     
    else    
    {   
      $('.js-responseBox').html(    
      `<h3>That's a wrong answer</h3>   
      <p>Correct Answer is:</p>   
      <p>${store[questionNumber].correctAnswer}</p>
      <button type="button" class="nextButton button">Next</button>`
      );
    }

   });
  }

     function generateOptions(questionNumber) {      
     return `<section class="textBox">    
         <legend>${store[questionNumber].question}</legend><br />
          <fieldset>
             <form id="myForm">
             <br />  
             <label>     
                <input class="answer" type="radio" name="option" ></input>    
                <span>${store[questionNumber].answers[0]}</span>       
             </label>       
             <br />    
             <label>    
            <input class="answer" type="radio" name="option"></input>    
            <span>${store[questionNumber].answers[1]}</span>    
          </label>    
          <br />    
          <label>    
            <input class="answer" type="radio" name="option"></input>    
            <span>${store[questionNumber].answers[2]}</span>    
          </label>    
          <br />    
          <label>   
            <input class="answer" type="radio" name="option"></input>    
            <span>${store[questionNumber].answers[3]}</span>   
          </label>    
          <br />   

我尝试了很多不同的方法

单击时表单中的提交按钮无法正常工作,它会将您带到上一页,好像什么也没发生

标签: javascriptjqueryhtmlcssforms

解决方案


可能是因为 textBox 对象是动态创建的,所以该元素的事件处理程序未正确附加。

尝试将选择器更改为附加事件处理程序时将出现在页面上的内容。

$(document).on(".textBox click",".submitButton",function (event) { //function contents });

这是有关此内容的更多信息的链接:https ://api.jquery.com/on/#direct-and-delegated-events

请参阅标题为“委托事件处理程序”的部分。


推荐阅读