更多帮助,不同的问题。我想从内部循环返回allLessonsArray,但由于某种原因它不会到达循环函数之外。我已经注意到它的工作原理,以及它不起作用的地方。如何将其退回到外面?
var allLessonsArray= new Array();
$.each(lessonInTopicSectionArray, function(index, lesson){
var lastAttempt = 0;
url='domain/learn/mod/lesson/report.php?id='+lesson.id+'&action=reportdetail&userid='+userid+'&try='+lastAttempt;
$.get(url, function(data) {
var lessonArray= new Array();
$(data).find('tr.r1.lastrow td.cell.c0')
.each(function(index, content) {
var string=jQuery(content).html()
score=parseInt(string.substr(string.length - 1));
lessonArray[index]=score;
});
allLessonsArray[index]={name:lesson.name, score: lessonArray};
//This works.
alert(allLessonsArray[0].name);
alert(allLessonsArray[0].score[0]);
});
//This doesn't work.
alert(allLessonsArray[0].name);
alert(allLessonsArray[0].score[0]);
});
return allLessonsArray;
答案 0 :(得分:2)
$.get()
是 AJAX 即。一个异步请求,所以你不能按你的意愿去做。
你可以这样做:
var allLessonsArray= new Array();
$.each(lessonInTopicSectionArray, function(index, lesson){
var lastAttempt = 0;
url='http://www.training-source.org/learn/mod/lesson/report.php?id='+lesson.id+'&action=reportdetail&userid='+userid+'&try='+lastAttempt;
$.get(url, function(data) {
var lessonArray= new Array();
$(data).find('tr.r1.lastrow td.cell.c0')
.each(function(index, content) {
var string=jQuery(content).html()
score=parseInt(string.substr(string.length - 1));
lessonArray[index]=score;
});
allLessonsArray[index]={name:lesson.name, score: lessonArray};
// check length to ensure that full array will return
if( allLessonsArray.length === lessonInTopicSectionArray.length )
reciever(allLessonsArray);
});
});
function receiver(allLessonsArray){
console.log(allLessonsArray);
}