2013-02-03 14 views
0

我试图完成如下:jQuery的回调函数同步与循环

1)for循环要经过一个产品列表,呼吁每个产品requestCrossDomain()函数。

2)函数requestCrossDomain()将每个产品的检索到的3组属性/描述传递回requestCross Domain()函数。

3)requestCrossDomain()函数完成后,使用循环闭包函数遍历属性/描述结果,并创建3个数组。知道这个函数一次只能在一个产品上工作很重要,这意味着如果for循环位于product [0]处,那么回调函数也应该在product [0]的属性/描述集上工作。

4)使用if()语句查找匹配集合,并返回数组/对象索引位置。

我被困在3),循环闭包似乎没有返回任何东西在console.log中。

//step 1) 
for (i=0; i<product.length; i++){ 
    ....  
    requestCrossDomain(arg[i], function(i) { //step 3) 
               //need to hold the i value 
     return function() {      //so the return function() is working on 
     var array = [];      //the matching product[i] 
     $('h4').each(function(j) { 
      array[j] = []; 
      var $this = $(this); 
      array[i][j] = { 
       Attribute: $this.text(), 
       Description: $this.next('p').text() 
      }; 

      //step 4) 
      if($this.text() == "Attr" && $this.next('p').text() == "Desc") { 
       console.log(i + "-" +j); //nothing return, no error message 
      }; 
     });   
     }; 

    }(i)); 
} 

//step 2) 
function requestCrossDomain(arg, callback) { 
    .... 
    // 3 sets of attribute/description are constructed here, the html will look like: 
    // <div> 
    // <h4>Attribute</h4> 
    // <p>Description</p> 
    // <h4>Attr</h4> 
    // <p>Desc</p> 
    // <h4>A</h4> 
    // <p>D</p> 
    // </div>  
    .... 
    callback(); 
} 

我猜测我没有完全理解for循环的回调函数。我的头脑已经旋转了几个小时,有人可以点亮吗?谢谢!

回答

0

我相信你的数组没有正确初始化。首先,你的意思是把

array[i] = []; //instead of array[j] right after $('h4').each(function(j) { 

?因为它使你的代码更有意义。如果你改变,然后添加

array[i][j] = []; 

作为下一行,我相信你应该很好去..让我知道。

此外,请尝试将console.log(“Step X”);无论你在哪里评论了一个步骤以确保达到了步骤,并且看看是否所有步骤都已到达/哪个步骤中断了。