I have a for loop:
for(var i = 0; i < r.length; i++){
var img=loadImage(r.id);
$gallery.append(img);
}
and loading image function:
function loadImage(id){
var $url='url/'+id;
var img = new Image();
$(img).load(function(){
return this;
})
.attr({'src':$url,'id':id});
}
in the function above, I want to return the img so I can use it in the for loop, but this does not seem to work, I don’t get image to show up. I know I can use $gallery.append(this) inside load which works well, but I need to use the above method for other purposes. so any suggestion that I can do it in this way? thanks.
Using jquery’s
loadevent to load images can be a bit buggy (taken from the jquery documentation) :In your case, I’d use one of two different approaches:
With callbacks, you have the power to execute some functionality when an asynchronous task is done :
With events, you have even more power…
You can create and trigger your own events and bind as many eventHandlers as you want.
An example of using personal events: