在下面的代码中,我有一个对元素进行计数的功能计数器。我使用counter函数来计算JSON文件中的元素。我的问题是如何在$ getJSON之后获取计数器的值,以及为什么在控制台记录括号之外的计数器时,我一直保持未定义状态,为什么它不记得最后一个值,而如果我在控制台记录日志,括号内的计数器,我得到JSON文件中元素的数量。我想获取元素的数量,因此以后可以在下面的for循环中使用该数量。
// global variables
var c = 0;
var a;
var b;
// counter function
function counter() {
return c++;
}
// document ready function
$(document).ready(function () {
$.getJSON("https://graph.facebook.com/v3.2/...", function (data) {
var items = [];
$.each(data.data, function (i, obj) {
//$('#target').append($('<div/>', { id: 'dummy' + i }))
var text = '<p class="review_text">' + obj.review_text + '</p>'
var date = '<p class="date">' + obj.created_time + '</p>'
a = counter();
$("#carousel").find("[data-index='" + i + "']").append(text, date)
console.log(a) //here I get the number of elements inside the JSON file
});
});
console.log(a) //but if I put the console log here, I get undefined instead of the number
var wrapper = document.getElementById("carousel");
var myHTML = '';
for (b = 0; b <= a; b++) { //here I want to use what the function returns, so if I have 10 elements in the JSON file I can create 10 div elements in the HTML, it works only if I put number instead of 'a' but I want to use 'a' so I do not have to count the elements as well, the elements will increase.
myHTML += '<div id="review" data-index=' + (b) + '></div>';
}
wrapper.innerHTML = myHTML
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
答案 0 :(得分:0)
在ajax调用中移动代码,以便在返回/处理数据后执行:
$(document).ready(function () {
$.getJSON("https://graph.facebook.com/v3.2/...", function (data) {
var items = [];
$.each(data.data, function (i, obj) {
//$('#target').append($('<div/>', { id: 'dummy' + i }))
var text = '<p class="review_text">' + obj.review_text + '</p>'
var date = '<p class="date">' + obj.created_time + '</p>'
a = counter();
$("#carousel").find("[data-index='" + i + "']").append(text, date)
console.log(a) //here I get the number of elements inside the JSON file
});
console.log(a) //but if I put the console log here, I get undefined instead of the number
var wrapper = document.getElementById("carousel");
var myHTML = '';
for (b = 0; b <= a; b++) { //here I want to use what the function returns, so if I have 10 elements in the JSON file I can create 10 div elements in the HTML, it works only if I put number instead of 'a' but I want to use 'a' so I do not have to count the elements as well, the elements will increase.
myHTML += '<div id="review" data-index=' + (b) + '></div>';
}
wrapper.innerHTML = myHTML;
});
});