简体   繁体   中英

jQuery callback function does not work

I'm trying to use the following code to make an image fadeOut and, only when it's faded out, change its source, and then make it fadeIn again:

$('.liitem').click(function() {
 $('#imagen').fadeOut('slow', function() {
  var rutaimagen = $(this).find('a').attr("href");
  $('#imagen').attr("src",rutaimagen).load(function(){     
   $('#imagen').fadeIn('slow');
   });
 });
 return false;
});

...but it doesn't work!! I've tried removing the callback function in fadeOut, and then it works but you can see for a moment the new image abruptly replacing the previous one (because it loads before the fadeOut effect has finished), then fading out, and then in again:

$('.liitem').click(function() {
 $('#imagen').fadeOut('slow');
  var rutaimagen = $(this).find('a').attr("href");
  $('#imagen').attr("src",rutaimagen).load(function(){     
   $('#imagen').fadeIn('slow');
   });
 return false;
});

Obviously I'd prefer a working version of the 1st snippet.

You can see that I am using a function that triggers the fadeIn effect only when the new image is loaded, which is logical in case the new image is very big and needs more time. I don't mind if it stays white while it loads, I can implement a loader .gif for that. But I don't know if this .load(function(){}); is interfering the whole thing.

One thing I notice that's different between your two examples:

$(this).find('a').attr("href");

In the first, "this" is #imagen, in the second "this" is .liitem. Does that have anything to do with it?

Thanks darkporter. This is my code now and it works:

$('.liitem').click(function() {
  var liitem = $(this);
 $('#imagen').fadeOut('slow', function() {
  var rutaimagen = liitem.find('a').attr("href");
  $('#imagen').attr("src",rutaimagen).load(function(){
   $('#imagen').fadeIn('slow');
   });
 });
 return false;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM