我有div通过AJAX请求填充divs
$(document).ready(function() {
question_block();
count_blocks();
});
function question_block() {
$.ajax({
url: '@Url.Action("QuestionBlocks", "Interwier")',
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'json',
processData: false,
success: function(result) {
var email = result;
for (var i = 0; i <= email.length - 1; i++) {
var question =
'<div class="activeQue" style="font-size:20px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">' +
email[i].Question1 +
'</div>' +
'<div class="hiddenQue" style="font-size:20px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">' +
email[i].Question2 +
'</div>' +
'<div class="hiddenQue" style="font-size:20px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">' +
email[i].Question3 +
'</div>' +
'<div class="hiddenQue" style="font-size:20px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">' +
email[i].Question4 +
'</div>' +
'<div class="hiddenQue" style="font-size:20px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">' +
email[i].Question5 +
'</div>' +
'<div class="hiddenQue" style="font-size:20px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">' +
email[i].Question6 +
'</div>' +
'<div class="hiddenQue" style="font-size:20px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">' +
email[i].Question7 +
'</div>' +
'<div class="hiddenQue" style="font-size:20px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">' +
email[i].Question8 +
'</div>' +
'<div class="hiddenQue" style="font-size:20px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">' +
email[i].Question9 +
'</div>' +
'<div class="hiddenQue" style="font-size:20px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">' +
email[i].Question10 +
'</div>';
$("#questions").append(question);
}
},
error: function() {
alert("Smth wrong in controller");
}
});
}
我需要计算父div中的div。我编写这段代码来获取所有div的计数:
function count_blocks() {
var length = $("#questions > div").length;
alert(length);
}
我这样打电话
$(document).ready(function() {
question_block();
count_blocks();
});
这里是查看HTML
<div id="questions" class="qustion-div-one" style="position: relative;"></div>
我的问题是,当我运行View时,我会通过length
= 0
我需要如何正确运行count_blocks
功能?
答案 0 :(得分:3)
问题是因为AJAX请求是异步的。这意味着当您调用count_blocks()
时页面加载时,页面中没有。要解决此问题,您需要在success
的{{1}}回调中调用该函数,如下所示:
$.ajax