jQuery:依次触发.click()事件 [英] jQuery: Triggering .click() events, one after the other
问题描述
我遇到这样的情况,我必须在页面上执行多项操作才能初始化它的设置.我还没有任何代码,因为坦率地说,我很难找到一个开始的地方.
I have a situation where I have to do multiple actions on a page in order to initialize it's settings. I do not have any code yet for it because, frankly I am having trouble finding a place to start on it.
这就是我想要做的:
jQuery(document).ready(function($) {
$('#element-one').trigger('click');
// wait for the first trigger event to complete (it loads ajax content into a div tag)
// then move on to this one...
$('#element-two').trigger('click');
// then move on to this one...
$('#element-three').trigger('click');
// then move on to this one...
$('#element-four').trigger('click');
// then finally move on to the last one
$('#element-five').trigger('click');
});
这是如何完成的?
推荐答案
在您的第一个处理程序中,您可以使用延迟的对象,在ajax成功回调中解析它并返回一个promise,这样您就可以像这样链接您的代码了(我没有尚未测试)
inside your first handler you could use a deferred object, resolve it in the ajax success callback and return a promise so you would chain your code like this (I haven't tested)
$.when(
$('#element-one').triggerHandler('click') /* asynchronous task */
).done(function() {
$('#element-two').triggerHandler('click') /* synchronous task */
...
$('#element-five').triggerHandler('click') /* synchronous task */
})
来自 http://api.jquery.com/category/deferred-object/
在1.5版中引入的jQuery.Deferred()是一个可链接的实用程序对象,可以将多个回调注册到回调队列中,调用回调队列,并中继任何同步或异步函数的成功或失败状态.
jQuery.Deferred(), introduced in version 1.5, is a chainable utility object that can register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.
注意:我使用的是triggerHandle()
而不是trigger()
: http://api.jquery.com/triggerHandler/只是与您附加了处理程序的元素无关.如果适合您的需求,请同时使用trigger()
Note: I used triggerHandle()
instead of trigger()
: http://api.jquery.com/triggerHandler/ just to be agnostic on elements to which you attached your handlers. Use trigger()
as well if it's suitable for your needs
这篇关于jQuery:依次触发.click()事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!