用.each()推迟的jQuery [英] JQuery deferred with .each()

查看:88
本文介绍了用.each()推迟的jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么想法如何将JQuery的延迟方法与可检测所有更改的表单并将其作为Ajax帖子提交的函数一起使用?

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();
});

我要开始使用的代码的完整版本在这里... 在JS Fiddle中

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

提前谢谢!

推荐答案

使用".map()"代替".each()":

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

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

$.when.apply(null, deferreds.get()).then(function() { ... });

使用"$ .when()"东西,您可以捆绑一堆延迟的对象,并等待它们全部成功(或者任何失败)-注意那里的区别.它通常允许任意数量的参数,但是由于我们有一个数组,所以我使用了"apply()".

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()".

请注意,我只使用了少量内容,因此请阅读jQuery API文档进行仔细检查:-) edit —同样,在重读您的问题时,我可能会误解您了.

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.

这篇关于用.each()推迟的jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆