-1

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

Invincible_Pain
  • 491
  • 2
  • 6
  • 17

2 Answers2

0

Using the on function, we can delegate that event to the elements and any that are added after the initial DOM load.

$('body').on('click', '.btn', () => {
  ...
})

Delegated event handlers have the advantage that they can process events from descendant elements that are added to the document at a later time

Cjmarkham
  • 9,484
  • 5
  • 48
  • 81
-1

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?

Allacassar
  • 159
  • 6