简体   繁体   中英

How do you bind newly added element without event like click, focus, etc?

For example if I want to bind datepicker to a newly added element. I could simply do this

$('body').on('focus', '.datepicker', function(){
    $(this).datepicker();
});​

but what if I don't want to use focus, I simply want to bind every element with .datepicker class on load. Is this possible?

After adding the elements dynamically, run code converting any that don't already have datepickers into ones that do. jQuery's datepicker adds a .hasDatepicker class when it initializes, so:

// After adding elements
$(".datepicker:not(.hasDatepicker)").datepicker();

If you really want to autmate it (perhaps you're not in control of the code that's adding the elements), you can use a MutationObserver on modern browsers (and polling on non-modern browsers; repeating the above every 50ms isn't going to add any significant overhead to your page).

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