So, I have this simple code
$('#info_name'+index).show("slide", {direction: "right"}, 1000, function(){
$('#info_info'+index).show('slide',{direction: "up"}, 1000);
});
The i
is declared upper as just a variable var i=0
, but in callback, function I can't see it...
var i = 0;
in the containing scope of the functions above, i
is definitely accessible within the callback - T.J. Crowder 2012-04-05 15:15
undefined
- Graham Clark 2012-04-05 15:20
There is a scope issue with i
. Since i
is declared in the outer scope, all callbacks will reference the same i
, meaning, if i
is changed, all callbacks' references to i
will also be changed.
What you can do is to create a function to generate the callback, since a new scope is created in that case, the value of i
will be preserved.
Based on the original question, I simplified the code a little bit. You've since edited it, and I can't find the callback anymore... but hope this might help ya
var getCallback = function(index) {
return function(){
// You can see how this index is being captured correctly in Javascript console
console.log(index);
$('#name' + index).show('slide',{direction: "up"}, 1000)
};
};
for (var i = 0; i < 3; ++i) {
$('#name'+i).show("slide", {direction: "right"}, 1000, getCallback(i));
}
JSFiddle: http://jsfiddle.net/vd9Mj/
UPDATE:
Where's your callback...? It seems you've removed it from the question.
var i=-1;
var doStuff = function(index) {
$('.third').append('<div class="showinfo"><h3 id="info_name'+i+'" class="info_name">'+contact_name[index]+'</h3><span class="info_info" id="info_info'+index+'"><strong>'+contact_information[0][0]+'</strong>: '+contact_number[index]+'</span></div>');
$('#info_name'+index).show("slide", {direction: "right"}, 1000);
$('#info_info'+index).delay(1000).show('slide',{direction: "up"}, 1000, function() {
// Insert code for callback.
});
};
$.each(contact_status, function(key, value){
i++;
if(value == info_id){
doStuff(i);
}
});
I'm not sure this will do what you want, even if i
was available - if you want your callback function to affect the element the event handler is attached to, use $(this)
:
$('#info_name'+i).show("slide", {direction: "right"}, 1000, function(){
$(this).show('slide',{direction: "up"}, 1000)
});