0

更多帮助,不同的问题。我想从内部循环返回 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;     
4

1 回答 1

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);
}
于 2012-08-16T16:34:44.260 回答