2016-12-07 40 views
0

這是我第一次嘗試在網站上實現AJAX。看來我的代碼在$(document).ready()上運行我的AJAX功能。我怎樣才能配置我的代碼聲明這些函數,而不是在頁面加載時運行?作用於頁面加載而不是按鈕點擊的AJAX函數

代碼:

$(document).ready(function(){ 

    var score = 0; //set result score to start at 0 

    $("#start").click(renderNewQuestion()); // get and render a new question when user clicks start 
    $("#nextQuestion").click(postResult()); // post result then get and render new question when user clicks next question 
    $("#answer-toggle").click(function(){ 
     $("#question").hide(); //hide question div 
     $("#answer").show(); //show answer div 
    }); 
    // omitted code to calculate score as irrelevant 

    var newQuestionHTML; //save HTML for new question in a variable 

    function getChunk(){ 
     $.ajax({ 
      type: 'GET', 
      url: '/getchunk/', 
      success: function(data) { 
       newQuestionHTML = html(data) 
      }, 
      error: function() { 
       alert('Something went wrong when getting the next question'); 
      } 
     }); 
    } 

    function renderNewQuestion(){ 
     getChunk; 
     $("review-row").replaceWith(newQuestionHTML); 
    } 

    function postResult(){ 
     var result = { 
      score: score, 
      csrfMiddlewareToken: $("input[name='csrfmiddlewaretoken']").val(), 
      chunkID: $("#chunk-id").val(), 
     }; 

     $.ajax({ 
      type: 'POST', 
      url: '/postresult/', 
      data: result, 
      success: renderNewQuestion(), 
      error: function() { 
       alert('Something went wrong when posting the results'); 
      } 
     }); 
    } 

}); 
+1

的可能的複製(http://stackoverflow.com/questions/15886272/什麼是函數調用和函數引用之間的區別)或http://stackoverflow.com/q/7102413/215552或http://stackoverflow.com/questions/10101899/javascript -onclick-event-getting-called-automatically或者http://stackoverflow.com/questions/29526556/javascript-onclick-function-is-called-immediately-not-when-clicked –

回答

1

在此行$("#start").click(renderNewQuestion());你應該傳遞給函數,不執行它,因此函數名後刪除括號。

這是它BTW寫一個更好的辦法:?是什麼函數調用和函數引用的區別]

$("#start").on("click", renderNewQuestion); 
相關問題