So as you all know that 1 trick of JS is that let’s say for example we bind a click event for all buttons on this page:
$(".btn").click(...)
<button class='btn'>A</button>
<button class='btn'>B</button>
then suddenly a button C was added to the page by JQuery append or AJAX, then there’s a problem that button C won’t get that event bind, you may have to do it in the maybe .js.erb or so.
This is very awkward and I’m wondering is there any better ways to handle this? Thanks
2
Answers
Using the on function, we can delegate that event to the elements and any that are added after the initial DOM load.
You should make an additional binding to new button at the time you add it.
here is a discussion of that matter: Event binding on dynamically created elements?