![](/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.