jQuery function after .append

后端 未结 19 2432
栀梦
栀梦 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 15:30

    Using MutationObserver can act like a callback for the jQuery append method:

    I've explained it in another question, and this time I will only give example for modern browsers:

    // Somewhere in your app:
    var observeDOM = (() => {
        var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
    
        return function(obj, callback){
            if( MutationObserver ){
                // define a new observer
                var obs = new MutationObserver(function(mutations, observer){
                    if( mutations[0].addedNodes.length || mutations[0].removedNodes.length )
                        callback(mutations);
                });
                // have the observer observe foo for changes in children
                obs.observe( obj, { childList:true, subtree:true });
    
                return obs;
            }
        }
    })();
    
    //////////////////
    // Your code:
    
    // setup the DOM observer (on the appended content's parent) before appending anything
    observeDOM( document.body, ()=>{
        // something was added/removed
    }).disconnect(); // don't listen to any more changes
    
    // append something
    $('body').append('

    foo

    ');

提交回复
热议问题