jQuery function after .append

后端 未结 19 2340
栀梦
栀梦 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:45

    I think this is well answered but this is a bit more specific to handling the "subChild_with_SIZE" (if that's coming from the parent, but you can adapt it from where it may be)

    $("#root").append(
        $('<div />',{
            'id': 'child'
        })
    )
    .children()
    .last()
    .each(function() {
        $(this).append(
            $('<div />',{
                'id': $(this).parent().width()
            })
        );
    });
    
    0 讨论(0)
  • 2020-11-27 15:45

    I know it's not the best solution, but the best practice:

    $("#root").append(child);
    
    setTimeout(function(){
      // Action after append
    },100);
    
    0 讨论(0)
  • 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 )

    0 讨论(0)
  • 2020-11-27 15:47

    I came across the same problem and have found a simple solution. Add after calling the append function a document ready.

    $("#root").append(child);
    $(document).ready(function () {
        // Action after append is completly done
    });

    0 讨论(0)
  • 2020-11-27 15:51

    Yes you can add a callback function to any DOM insertion:
    $myDiv.append( function(index_myDiv, HTML_myDiv){ //.... return child })

    Check on JQuery documentation: http://api.jquery.com/append/
    And here's a practical, similar, example: http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_html_prepend_func

    0 讨论(0)
  • 2020-11-27 15:52
    $('#root').append(child).anotherMethod();
    
    0 讨论(0)
提交回复
热议问题