简体   繁体   中英

How do I bind a “data appended” event in js / jquery?

At the moment, I have a piece of code looking like this:

$("#somediv").append(data);
somethingToDoAfterDataAppended();

It seems that the data is appended asynchronously, therefor the next function is not necessarily invoked after data is actually appended.

I was thinking about a way to bind this function with 'data appended' event - is it possible?

Any other solution would be equally useful.

It simple. You can change the append method and insert there a trigger(s) for you special event.

$.fn.append = (function(old){
   return function(){

       $(this).trigger('beforeAppend'); // if needed
       var result = old.apply(this,arguments);
       $(this).trigger('afterAppend');
       return result;

       }

    })($.fn.append);

Somewhere in your initialization logic:

$("#somediv").bind('afterAppend',somethingToDoAfterDataAppended);

And :)

("#somediv").append(data); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM