duanbiao4025 2015-06-30 00:23
浏览 387
已采纳

为什么preventDefault函数总是不起作用?

I'm trying to create a quiz with PHP and Javascript.

After a user clicked for an answer, an ajax request starts and the result is been given in the response. If it was true, the clicked button gets a 'success' class and if false, a 'wrong' class.

After this the buttons are disabled and the user can click to the next question. But the problem is, that after one or two questions, the javascript function doesn't work and the default action of the form is being called.

$(document).ready(function(){

    // Get the form.
    var form = $('#bilderquiz');

    // Set up an event listener for the contact form.
    $(form).submit(function(e) {
        // Stop the browser from submitting the form.
        

        // Serialize the form data.
        var formData = $(form).serialize();

        // Submit the form using AJAX.
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            data: formData
            , async: false
        })
        .done(function(response) {
            
            var submittedAnswer = $("input[type=submit][clicked=true]");
            var allAnswers = document.querySelectorAll( ".answerButton" );
            
            alert(response);
            
            if(response == 'trueAnswer'){
                submittedAnswer.removeClass('wrongAnswer');
                submittedAnswer.addClass('trueAnswer');
                $(".answerButton").attr('disabled', true);
            } else{
                submittedAnswer.removeClass('trueAnswer');
                submittedAnswer.addClass('wrongAnswer');
                $(".answerButton").attr('disabled', true);
            }
        })
        .fail(function(data) {

            // Set the message text.
            if (data.responseText !== '') {
                $(formMessages).text(data.responseText);
            } else {
                $(formMessages).text('Oops! An error occured and your message could not be sent.');
            }
        });

    });
    
});

function setClicked(input){
    $(input).parents("form").removeAttr("clicked");
    $(input).attr("clicked", "true");
}
<div class="answerChar">A</div>
              <form id="bilderquiz" action="includes/functions.php" method="post">
                <button class="answerButton" type="submit" id="selection" name="selection" value="0" onclick="setClicked(this)">
                  <?php echo $questionData['answerButtons'][0] ;?>
                </button>
              </form>   
            </div>
            <div class="col-sm-6">
              <div class="answerChar">B</div>
              <form id="bilderquiz" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
                <button class="answerButton" type="submit" id="selection" name="selection" value="1" onclick="setClicked(this)">
                  <?php echo $questionData['answerButtons'][1];?>
                </button>
              </form> 
            </div>
          </div>
          <div class="row">
            <div class="col-sm-6">
              <div class="answerChar">C</div>
              <form id="bilderquiz" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
                <button class="answerButton" type="submit" id="selection" name="selection" value="2" onclick="setClicked(this)">
                  <?php echo $questionData['answerButtons'][2];?>
                </button>
              </form> 
            </div>
            <div class="col-sm-6">
              <div class="answerChar">D</div>
              <form id="bilderquiz" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
                <button class="answerButton" type="submit" id="selection" name="selection" value="3" onclick="setClicked(this)">
                  <?php echo $questionData['answerButtons'][3];?>
                </button>
              </form> 
            </div>
          </div>
          <div class="row">
            <div class="col-sm-12">
            <form id="bilderquiz" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
              <button class="submitButton" type="submit" id="selection" name="selection" value="4" onclick="setClicked(this)">Nächste Frage</button>
            </form> 
            </div>
          </div>

My second problem is, that this lines also doesn't work:

submittedAnswer.removeClass('wrongAnswer');
submittedAnswer.addClass('trueAnswer');

</div>
  • 写回答

1条回答 默认 最新

  • dongwan0574 2015-06-30 01:07
    关注

    Your forms need unique IDs, right now they are all id="bilderquiz" Or you could use classes.

    The php:

    <form class="capture-me">...</form>
    <form class="capture-me">...</form>
    

    The JS:

    $('form.capture-me').on('submit',function(e){ .....
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 slam rangenet++配置
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊