开发者

How to deal with the callback being called multiple times when animating more than one thing in jQuery

开发者 https://www.devze.com 2023-01-06 03:34 出处:网络
Consider this code... $(function() { for (var i = 0; i < 10; i++) { $(\'body\').append(\'<开发者_开发百科;div style=\"width: 30px; height: 30px; background: red; margin: 10px;\" />\')

Consider this code...

$(function() {

  for (var i = 0; i < 10; i++) {
    $('body').append('<开发者_开发百科;div style="width: 30px; height: 30px; background: red; margin: 10px;" />')

    }

      $('div').slideUp(1000, function() {

        $('body').append('done sliding');

      });

});

(see it on JSbin)

It creates 10 divs and then slides them up. The callback is called 10 times, when I would prefer it to be called once (after all have finished sliding).

I know I could do a Boolean or something, like hasCalledCallback, but is there any other more elegant way to make multiple elements animating call a completion callback only once?


try this

if ($('div:animated').length == 1)
        $('body').append('done sliding');

demo


One possibility is to use setTimeout:

$(function() {

  for (var i = 0; i < 10; i++) {
    $('body').append('<div style="width: 30px; height: 30px; background: red; margin: 10px;" />');
  }

  var timerid;
  $('div').slideUp(1000, function() {
    clearTimeout(timerid);
    timerid = setTimeout(function() {$('body').append('done sliding')}, 100);
  });
});

To actually avoid calling the callback multiple times, only add it to the last div:

$(function() {

  var lastDiv, otherDivs = [];
  for (var i = 0; i < 10; i++) {
    div = $('<div style="width: 30px; height: 30px; background: red; margin: 10px;" />');
    $('body').append(div);
    if(i == 9) lastDiv = div;
    else otherDivs.push(div);
  }

  $.each(otherDivs, function(index, val) {
    val.slideUp(1000);
  });
  lastDiv.slideUp(1000, function() {
    $('body').append('done sliding');
  });
});

You could do that last part without the lastDiv and otherDivs variables by adding classes to the divs and selecting on those.

0

精彩评论

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