How would I use .on() if the HTML is not generated yet? The jQuery page says
If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page.
But I’m not really sure how to do that. Is there a way to “reload” the event handler?
So if I had
$(document).ready(function(){
$('.test').on('click', function(){
var id = $(this).attr('id');
console.log("clicked" + id);
});
generatePage();
});
where generatePage() creates a bunch of divs with .test, how would I rebind .on()?
I’m aware similar questions have been asked, but I didn’t find what I was looking for after a quick search.
Use .on like in the example below. One can presume that the body-tag is always available so it’s safe to attach the event handler to body and delegate the events to the selector, in this case .test.
Or if generatePage() is also generating the html, head and body tags use document as your selector.
According to the jquery documentation .on accepts the following parameters:
Including selector is described as follows: