JQuery deferred with .each()

耗尽温柔 提交于 2019-12-30 00:39:09

问题


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 working if I just list a load of form submissions but if I use...

$('form.changed').each(function(){
  return $(this).submitWithAjax();
});

A fuller version of the code that I'm trying to get working is here... at JS Fiddle

Thanks in advance!


回答1:


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.




回答2:


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!')
});


来源:https://stackoverflow.com/questions/6162855/jquery-deferred-with-each

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!