2012-08-16 84 views
0

更多帮助,不同的问题。我想从内部循环中返回allLessonsArray,但由于某种原因,它不会到达循环函数之外。我已经注意到它在哪里工作,哪里不起作用。我如何将其返回到外部?jQuery范围,。每个

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

不用彷徨的'异步行为()'导致您的问题。 – j08691 2012-08-16 16:35:34

回答

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); 
} 
+0

有没有办法在最后一次迭代之后返回完整数组? – 2012-08-16 16:39:34

+0

@JoeTuskan先生,我已经更新过。谢谢 – thecodeparadox 2012-08-16 16:40:03

+0

@NathanLothamer请尝试更新。 – thecodeparadox 2012-08-16 16:40:39