如何在jQuery中编写一个循环,等待每个函数完成后再继续循环 [英] How to write a loop in jQuery which waits for each function to complete before continuing the loop

查看:828
本文介绍了如何在jQuery中编写一个循环,等待每个函数完成后再继续循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果这很明显,请原谅我.

Please forgive me if this is an obvious one.

页面上的元素数量未知,我需要一次遍历一个元素并对其进行处理.但是,我需要循环来暂停,直到元素上使用的功能完成,然后继续进行下一个迭代.

I have an unknown amount of elements on a page, which I need to loop through one at a time and do stuff to. However, I need the loop to pause until the functions used on the elements have completed, and then continue on to the next iteration.

我尝试在$ .each循环中执行此操作,但是它很快就触发了命令,并且无需等待它们完成就可以完成.

I tried doing this in a $.each loop, but it fired off the commands far to quickly and finished without waiting for them to complete.

有什么想法吗?

$('elem').each(function(){
    $(this).fadeIn().wait(5000).fadeOut();
});

这就是我所拥有的,非常简单. 我从这里获得了wait()函数: jquery食谱网站.

This is what I have, very simple. I got the wait() function from here: jquery cookbook site.

问题是,循环 doesnt 等待-实际命令按预期工作,只是它们一次全部消失.

Problem is, the loop doesnt wait - the actual command works as intended, it's just that they all go off at once.

任何帮助表示感谢,谢谢.

Any help appreciated, thanks.

执行完此操作后,我可能想再次执行循环,以使元素列表按顺序再次淡入/淡出

After this is executed, I may want to then execute the loop again, so that the list of elems will be faded in / out again in sequence

自从有了1.4.2 jQuery lib之后,就使用了1.3.2,因此使用了自定义的wait()函数.现在使用lobstrosity提到的delay(). 感谢lobstrosity :)设法将他的答案中的内容与我所需的内容相提并论.

Have since gotten the 1.4.2 jQuery lib, was using 1.3.2, hence the custom wait() function. Now using delay() as mentioned by lobstrosity. Managed to cobble together something close to what I need from his answer, thanks lobstrosity :) .

推荐答案

首先,jQuery 1.4添加了 delay 函数,我假设这是您的自定义等待实现所执行的操作.

First of all, jQuery 1.4 added the delay function, which I assume is what your custom wait implementation is doing.

使用延迟,您可以通过将每个回调的第一个参数用作初始延迟的乘数,来假冒每个元素在上一个元素上等待"完成的功能.像这样:

Using delay, you can sort of fake the functionality of each element "waiting" on the previous element to finish by using the first parameter to the each callback as a multiplier for an intial delay. Like this:

var duration = 5000;

$('elem').each(function(n) {
    $(this).delay(n * duration).fadeIn().delay(duration).fadeOut();
});

因此第一个元素将立即淡入.秒钟将在5,000毫秒后淡入. 10,000毫秒后的第三个,依此类推.请记住,这是伪造的.每个元素实际上并没有等待上一个元素结束.

So the first element will fadeIn immediately. The second will fadeIn after 5,000 ms. The third after 10,000 ms and so on. Keep in mind that this is faking it. Each element is not actually waiting on the previous element to finish.

这篇关于如何在jQuery中编写一个循环,等待每个函数完成后再继续循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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