jQuery: Triggering .click() events, one after the other

后端 未结 1 1088
小蘑菇
小蘑菇 2021-01-18 06:32

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 troubl

1条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-18 06:55

    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 */
     })
    

    from http://api.jquery.com/category/deferred-object/

    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.

    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

    0 讨论(0)
提交回复
热议问题