JQuery deferred with .each()

后端 未结 2 1733
醉酒成梦
醉酒成梦 2020-12-28 23:46

Any ideas how you might use JQuery\'s deferred methods with a function that detects all changed forms and submits each one as an Ajax post?

I can get the same thing

相关标签:
2条回答
  • 2020-12-29 00:10

    Instead of ".each()", use ".map()":

    var deferreds = $('form.changed').map(function(i, elem) {
      return $(this).submitWithAjax();
    });
    
    $.when.apply(null, deferreds.get()).then(function() { ... });
    

    The "$.when()" thing lets you bundle up a bunch of deferred objects and wait for all of them to succeed (or for any to fail — note the difference there). It normally allows an arbitrary number of arguments, but since we've got an array I used "apply()".

    Note that I've only used this stuff lightly, so read the jQuery API docs to double check :-) edit — also upon re-reading your question, I may have misunderstood you.

    0 讨论(0)
  • 2020-12-29 00:16

    Delegating the change event to the form fields could solve your problem here.

    $('form').delegate('input[type=text], input[type=radio], select', 'change', 
    function(evt){
        // your submits here
        console.log('changed!')
    });
    
    0 讨论(0)
提交回复
热议问题