我試圖完成如下: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循環的回調函數。我的頭腦已經旋轉了幾個小時,有人可以點亮嗎?謝謝!