0
for (var i = 0; i < friends.length; i++) {
    var friend = $("<li>" + friends[i].name + "</li>");
    FB.api('/' + eventId + '/invited/' + friends[i].id, 'post', {}, function (response) {
        //friend here is the last one created for all callbacks
    });
}

我有一个邀请朋友参加活动的循环,我发现friend这里创建的 jquery 对象始终是为所有回调创建的最后一个对象。我假设这是因为 Facebook 调用是异步的。我怎样才能在这里保持范围?

4

2 回答 2

2

您可以为局部变量创建一个闭包:

for (var i = 0; i < friends.length; i++) {
  var friend = $("<li>" + friends[i].name + "</li>");

  (function(friend){

    FB.api('/' + eventId + '/invited/' + friends[i].id, 'post', {}, function (response) {
      //friend here is the parameter in the closure, so it's preserved for each item
    });

  })(friend);

}
于 2012-05-22T11:32:23.543 回答
1

尝试这个:

for (var i = 0; i < friends.length; i++) {
    var friend = $("<li>" + friends[i].name + "</li>");
    var callback = (function(friend){
       return function (response) {
          //friend here should be the correct one
       })(friend);
    }
    FB.api('/' + eventId + '/invited/' + friends[i].id, 'post', {}, callback);
}
于 2012-05-22T11:30:19.893 回答