2013-02-03 47 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」);無論你在哪裏評論了一個步驟以確保達到了步驟,並且看看是否所有步驟都已到達/哪個步驟中斷了。