I\'m stuck with a situation where my DOM elements are generated dynamically based on $.getJSON
and Javascript functions for this elements are not working. I\'ll
Instead of calling on
directly on the element, call it on a parent that isn't dynamically added and then use the optional selector
parameter to narrow it to the element.
$('.parent').on('click', '.element', () => {
// do something
});
The difference between this and:
$('.element').on('click', () => {});
is with $('.element').on()
, you're only applying the listener to the elements that are currently in that set. If it's added after, it won't be there.
Applying it to $(.parent)
, that parent is always there, and will then filter it to all of it's children, regardless when they're added.