![](/img/trans.png)
[英]How to get on click button to load the nav tab page at the top rather than in the middle?
[英]AJAX functions acting on page load rather than button click
這是我第一次嘗試在網站上實現AJAX。 看來我的代碼在$(document).ready()
上運行了我的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');
}
});
}
});
在此行$("#start").click( renderNewQuestion());
您應該傳遞函數,而不是執行它,因此請在函數名稱后刪除括號。
這是寫它的更好的方法:
$("#start").on("click", renderNewQuestion);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.