jQuery function after .append

后端 未结 19 2402
栀梦
栀梦 2020-11-27 15:25

How to call a function after jQuery .append is completely done?

Here\'s an example:

$(\"#root\").append(child, function(){
   // Action          


        
19条回答
  •  余生分开走
    2020-11-27 15:47

    I'm surprised at all the answers here...

    Try this:

    window.setTimeout(function() { /* your stuff */ }, 0);
    

    Note the 0 timeout. It's not an arbitrary number... as I understand (though my understanding might be a bit shaky), there's two javascript event queues - one for macro events and one for micro events. The "larger" scoped queue holds tasks that update the UI (and DOM), while the micro queue performs quick-task type operations.

    Also realize that setting a timeout doesn't guarantee that the code performs exactly at that specified value. What this does is essentially puts the function into the higher queue (the one that handles the UI/DOM), and does not run it before the specified time.

    This means that setting a timeout of 0 puts it into the UI/DOM-portion of javascript's event queue, to be run at the next possible chance.

    This means that the DOM gets updated with all previous queue items (such as inserted via $.append(...);, and when your code runs, the DOM is fully available.

    (p.s. - I learned this from Secrects of the JavaScript Ninja - an excellent book: https://www.manning.com/books/secrets-of-the-javascript-ninja )

提交回复
热议问题