如何按顺序执行jquery函数? [英] how to execute jquery functions in a order?

查看:395
本文介绍了如何按顺序执行jquery函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所述,如何维护/控制Jquery中函数的执行顺序?我知道我们可以通过addEventListener建立许多事件处理程序,但是不能保证它们的执行顺序.让我引用

As the title says, how can I maintain/control the order of execution of functions in Jquery? I know we can establish many event handler via addEventListener, but the order of their execution isn't guaranteed. Let me quote

请注意,即使处理程序按照其处理顺序触发 已建立,此订单不符合标准!测试人员 这段代码从未观察到除以下命令之外的其他命令 建立,但是编写依赖于此的代码将是愚蠢的 这个命令.请务必注意,在一个 元素可能会以随机顺序触发.

Note that even though the handlers fire in the order in which they were established, this order isn’t guaranteed by the standard! Testers of this code never observed an order other than the order of establishment, but it would be foolish to write code that relies on this order. Always be aware that multiple handlers established on an element may fire in random order.

Manning Jquery in Action 2nd Edition

此外,我们可以使用queue()方法以特定的顺序执行 trick jQuery(AFAIK)执行处理程序,然后调用dequeue()方法来调用该队列中的方法.创建队列时定义的顺序. 但这不是一个永久性的解决方案,因为尽管出队确实按照定义的顺序执行了它们,但是在执行后也将它们从队列中删除.因此,这是一个一次性的解决方案,一旦我们完成了队列的处理,顺序(为此我们首先创建了队列!)就消失了.

Also, we can trick jquery (AFAIK) into executing the handlers in a particular order by using queue() method, and call the dequeue() method to invoke the methods inside that queue, in the order defined when creating the queue. But this is not a permanent solution, as, though dequeue does executes them in the order defined, but also removes them from queue after executing. So, this is a one time solution, once we are done with the queue, the order (for the sake of which we created the queue in first place!) is gone.

所以,我想知道,是否有解决方法或解决方案?如果是这样,这是否取决于我们的要求?像处理click事件,还是通过使用Ajax加载来加载异步数据?

So, I wanna know, is there a workaround or a solution for this or not? And if so, does that depends on our requirements? Like handling the click event, or loading async data via load using ajax?

推荐答案

我知道我们可以通过 addEventListener 建立许多事件处理程序,但是不能保证它们的执行顺序."

对于与addEventListener()绑定的事件处理程序,不能保证执行顺序,但是对于与jQuery绑定的事件处理程序,绝对可以保证 执行顺序. jQuery以绑定它们的顺序调用处理程序.

Order of execution isn't guaranteed for event handlers bound with addEventListener(), but order of execution definitely is guaranteed for event handlers bound with jQuery. jQuery calls your handlers in the same order they were bound.

这在jQuery文档中的粗体字中并没有很明显,但是如果您看上去很努力的话,它会在 中出现.从 .on()方法doco :

This isn't made very obvious in giant bold text in the jQuery documentation, but it is there if you look hard enough. From the .on() method doco:

(绑定到元素的事件处理程序的调用顺序与绑定它们的顺序相同.)

或更详细的 .bind()方法

Or in more detail from the .bind() method

当事件到达某个元素时,将触发绑定到该事件类型的该元素的所有处理程序.如果注册了多个处理程序,则它们将始终按照绑定的顺序执行.执行完所有处理程序后,事件将沿着正常的事件传播路径继续.

这篇关于如何按顺序执行jquery函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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