skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. 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?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search