我想创建大约 10 个 XML HTTP 请求,如下所示。我想将 i
的值用于第一个“子级”引用,但是随着 i
在执行回调之前发生变化,i
的值code> 与“结果”选项卡中的 url 不匹配。我如何概括这一点?
var i = 1;
WinJS.xhr({
url: root.results[i].profile_image_url_https,
responseType: 'blob'
}).done(function (result) {
var imgTag = theDiv.children[1].children[0];
var imageBlob = URL.createObjectURL(result.response, {
oneTimeOnly: true
});
imgTag.src = imageBlob; //tempLocalUrl;
});
i = 2;
WinJS.xhr({
url: root.results[i].profile_image_url_https,
responseType: 'blob'
}).done(function (result) {
var imgTag = theDiv.children[2].children[0];
var imageBlob = URL.createObjectURL(result.response, {
oneTimeOnly: true
});
imgTag.src = imageBlob; //tempLocalUrl;
});
最佳答案
典型的方法是使用一个额外的函数(立即执行)来捕获循环变量的当前值,例如:
var i = 1;
WinJS.xhr({
url: root.results[i].profile_image_url_https,
responseType: 'blob'
}).done(function (inner_i) {
// return the actual callback
return function (result) {
// use `inner_i` as needed
var imgTag = theDiv.children[1].children[0];
var imageBlob = URL.createObjectURL(result.response, {
oneTimeOnly: true
});
imgTag.src = imageBlob; //tempLocalUrl;
};
}(i)); // <= pass outer `i`
关于javascript - javascript回调函数的泛化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13643047/