简体   繁体   中英

Initialize jquery plugin on dynamic elements

I have this code

$(".address-geocomplete").geocomplete({
    country: "US",
    details: ".details",
    detailsAttribute: "data-geo"
});

It works with no problem when the elements were loaded with the document but it doesn't work when the element is called with ajax. I understand I could add the function to the ajax call but that's what I don't want. I would want to write this function once and for it to work no matter if the element was called on the document load or in ajax. Is that possible to do? How? Thanks

Use MutationObserver . You can use it to detect additions to the DOM. Watch the element to which the children are added, filter out the new child elements with class address-geocomplete and run your jQuery code on them.

MutationObserver does not work on old IE versions (10 and older).

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