简体   繁体   中英

How to call a function when a div is dynamically generated using jQuery

The scenario I want to achieve is as follow:

$("#parentDiv").on("load",'#childDiv', function () {
        // do something...
});

I would like to call a function when a child div is dynamically generated and shown on the page, but there is no suitable event that can achieve this. Any hint or help would be appreciated.

Instead of load , you can make use of a custom event which gets triggered with .trigger() :

 $(document).ready(function() { $("button").on("click", function() { $("body").append("<div id='new'>Created</div>").trigger('custom-event'); }); }); $(document).on("custom-event", function() { console.log('DIV created!'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <button>Create element</button> </body> 

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