how to execute jquery functions in a order?

后端 未结 3 1225
梦如初夏
梦如初夏 2021-01-26 16:52

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 th

相关标签:
3条回答
  • 2021-01-26 17:09

    Why use multiple event handlers if you need code to execute in a particular order?

    It will generally lead to much more maintainable and obvious code if you use one event handler that executes your multiple function calls in your desired order.

    0 讨论(0)
  • 2021-01-26 17:13

    I could use callback functions and handle events in these functions.

    function helloWorld(hello,callback)
    {
       //does something here with hello 
       callback(); //calls the callback function for final execution
    }
    
    helloWorld("world",alertUser);
    
    function alertUser(){
      alert("I am done with this function");
    }
    

    So if I understood your question OK, then I do something like the above.

    0 讨论(0)
  • 2021-01-26 17:28

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

    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.

    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:

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

    Or in more detail from the .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.

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