简体   繁体   English

使用jQuery动态生成div时如何调用函数

[英]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. 当子div动态生成并显示在页面上时,我想调用一个函数,但是没有合适的事件可以实现此目的。 Any hint or help would be appreciated. 任何提示或帮助,将不胜感激。

Instead of load , you can make use of a custom event which gets triggered with .trigger() : 您可以使用.trigger()触发的自定义事件来代替load

 $(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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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