javascript - 如何按顺序执行jquery函数?

标签 javascript jquery jquery-plugins

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

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 第二版

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

所以,我想知道,是否有解决方法或解决方案?如果是这样,这取决于我们的要求吗?比如处理点击事件,或者使用ajax通过load加载异步数据?

最佳答案

"I know we can establish many event handler via addEventListener, but the order of their execution isn't guaranteed."

对于与 addEventListener() 绑定(bind)的事件处理程序,不保证执行顺序,但对于与 jQuery 绑定(bind)的事件处理程序,执行顺序绝对保证jQuery 按照绑定(bind)顺序调用您的处理程序。

这在 jQuery 文档中的巨大粗体文本中并没有表现得非常明显,但如果您仔细观察,它就在那里。来自 .on() method doco :

(Event handlers bound to an element are called in the same order that they were bound.)

或者从 .bind() method 获取更多详细信息

When an event reaches an element, all handlers bound to that event type for the element are fired. If there are multiple handlers registered, they will always execute in the order in which they were bound. After all handlers have executed, the event continues along the normal event propagation path.

关于javascript - 如何按顺序执行jquery函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11920504/

相关文章:

javascript - 从谷歌地理编码结果中删除奇怪的日文字符

两个 iframe 连接的 Javascript

javascript - 我可以循环遍历数据表列对象并添加+2的新行添加吗

javascript - 从动态生成的元素读取数据时出错

javascript - 用 JS 比较当前和给定时间

javascript - 使用 JS 淡化多个 div

javascript - 我的 jQuery 插件无法正常工作。 TypeError : $(. ..).functionName 不是函数

javascript - history.go(-1) 返回在 Chrome 中不起作用

JQuery 访问插件中的变量

javascript - 在查询中选择该类中的所有类