Looping through results in jQuery
I get stacked on a looping issue and couldn't get it.
for (var i = 0; i < count; i++) {
FB.api({
method: 'fql.query',
query: 'SELECT name FROM user WHERE uid=' + temparray[i]
},开发者_如何学编程 function (response) {
for (var x = 0; x < count; x++) {
$("#divfather" + x).html(response[0].name);
}
});
}
The second loop is done through response[0].name
which is the name of Facebook and showing me the same response for all divs.
I want only this second loop being done to the i
variable.
How can I do it?
It's a little hard to understand what you want, but I assume you only want the i
from the outer for
loop.
You'll need to create a new variable scope in order to retain it.
for (var i = 0; i < count; i++) {
FB.api({
method: 'fql.query',
query: 'SELECT name FROM user WHERE uid=' + temparray[i]
}, (function( j ) { // <---- create a function...
// v---------...that returns a function...
return function (response) {
$("#divfather" + j ).html(response[0].name);
};
})( i ) // <------...and invoke it immediately, passing "i"
);
}
Here's the same thing, but using a named function, which I think is a little nicer.
function get_callback( j ) {
return function (response) {
$("#divfather" + j ).html(response[0].name);
};
}
for (var i = 0; i < count; i++) {
FB.api({
method: 'fql.query',
query: 'SELECT name FROM user WHERE uid=' + temparray[i]
}, get_callback( i ) );
}
Or personally, I'd place all the logic in the function instead of splitting it up.
function set_up_FB_api( j ) {
FB.api({
method: 'fql.query',
query: 'SELECT name FROM user WHERE uid=' + temparray[ j ]
}, function (response) {
$("#divfather" + j ).html(response[0].name);
});
}
for (var i = 0; i < count; i++) {
set_up_FB_api( i );
}
You have a scope issue sken boy.
You are using i
in the outer loop and then redeclaring it in the inner loop.
Change the second loop to some other letter like x
.
精彩评论