开发者

jQuery toggle() problem

  $('.toggle').toggle(function(){
    var ul = $('ul');
    ul.fadeOut('fast', function(){
      ul.fadeIn('fast').removeClass(开发者_如何学C'off');
      ul.addClass('on');
    });
  }, function(){
    ul.fadeOut('fast', function(){
      alert('wtf'); // <- never gets here...
      ul.fadeIn('fast').removeClass('on');
      ul.addClass('off');
    });
  });

What am I doing wrong??

Any code that I add inside the second fadeOut callback function never gets executed...


Put var ul = $('ul'); in your second function too.


ul is not defined in the second callback. Change its scope so it is visible to both callbacks.

var ul = $('ul');

$('.toggle').toggle(function(){
  ul.fadeOut('fast', function(){
    ul.fadeIn('fast').removeClass('off');
    ul.addClass('on');
  });
}, function(){
  ul.fadeOut('fast', function(){
    ul.fadeIn('fast').removeClass('on');
    ul.addClass('off');
  });
});

If you don't want ul to be in scope outside of this, either wrap it in a self invoking function or specify the ul within each callback of toggle().


The variable ul doesn't exist in the scope of the second function. It's actually a bit of an unneeded optimization in your case, since the following should also work:

  $('.toggle').toggle(function(){
    $('ul').fadeOut('fast', function(){
      $(this).fadeIn('fast').removeClass('off').addClass('on');
    });
  }, function(){
    $('ul').fadeOut('fast', function(){
      $(this).fadeIn('fast').removeClass('on').addClass('off');
    });
  });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜