开发者

jQuery, Wait for another function

开发者 https://www.devze.com 2022-12-17 22:18 出处:网络
I\'m rather new to jQuery and have a quick question. I have two jQuery functions which both seems to start onload, but I want to delay the one function until the first function has completed:

I'm rather new to jQuery and have a quick question.

I have two jQuery functions which both seems to start onload, but I want to delay the one function until the first function has completed:

$(document).ready(开发者_如何学编程function() {
//DO SOME AJAX STUFF HERE AND CALL FUNCTION TWO BELOW WHEN DONE
});

jQuery(document).ready(function() {
    jQuery('#mycarousel').jcarousel({            
        itemLoadCallback: { onBeforeAnimation: mycarousel_itemLoadCallback }
    });
});


You should call the second function from the callback of the first ajax function.

For example:

$(document).ready(function() {
   MyAjaxMethod(function() {

       jQuery('#mycarousel').jcarousel({            
           itemLoadCallback: { onBeforeAnimation: mycarousel_itemLoadCallback }
       });

   });
}


The Ajax method in jQuery has a callback parameter which you can use to specify a function that should be called when the request has completed. For example:

$(function()
{
    $.ajax('url', {}, function(data)
    {
        // Do your stuff here.
    }, 'json');
});

Also, note that $(function()... is equivalent to $(document).ready(function()... but is more concise!


All Ajax functions have callbacks that are executed when the processing is completed. This is the recommended way of doing things in jQuery.

For example:

$("selector").load(url, function() {
  // Put your second function here
});


$.get and and $.post both allow callbacks:

jQuery.post( url, [data], [callback], [type] )

So get the jcarousel method to run once the post has completed:

$(document).ready(function() {
    $.post(url, data, function(
      jQuery('#mycarousel').jcarousel({            
         itemLoadCallback: { onBeforeAnimation: mycarousel_itemLoadCallback }
     });

    ));
});
0

精彩评论

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

关注公众号