Jquery .when and multiple .load

前端 未结 2 1810
情书的邮戳
情书的邮戳 2020-12-08 08:54

I want to have one callback function after actions are done, I\'m trying something like this:

$.when(
    $(\'#detail1\').load(\'/getInfo.php\'),
    $(\'#de         


        
相关标签:
2条回答
  • 2020-12-08 09:12

    I do a similar code but for images in a more dynamic way. Hope that it help.

    var deferreds = [];
    // Create a deferred for all images
    $('.my-img-class').each(function() {
        deferreds.push(new $.Deferred());
    });
    var i = 0;
    // When image is loaded, resolve the next deferred
    $('.my-img-class').load(function() {
        deferreds[i].resolve();
        i++;
    });
    // When all deferreds are done (all images loaded) do some stuff
    $.when.apply(null, deferreds).done(function() { 
        // Do some stuff
    });
    
    0 讨论(0)
  • 2020-12-08 09:24

    This is because jQuery.when() expects jQuery.Deferred instances while load() returns an jQuery instance (see http://api.jquery.com/jQuery.when/ and http://api.jquery.com/load/).

    You can work around this issue:

    // Create two Deferred instances that can be handed to $.when()
    var d1 = new $.Deferred();
    var d2 = new $.Deferred();
    
    // Set up the chain of events...
    $.when(d1, d2).then(function() {
        alert('done');
    });
    
    // And finally: Make the actual ajax calls:
    $('#detail1').load('/getInfo.php', function() { d1.resolve(); });
    $('#detail2').load('/getOther.php', function() { d2.resolve(); });
    
    0 讨论(0)
提交回复
热议问题