0

I have links in a list that fires some jQuery activity:

HTML:

<div id="list">
<a href="#" rel="23" class="edit">Edit:</a> Foo
<a href="#" rel="24" class="edit">Edit:</a> Bar
etc.

jQUERY:

$('.edit').click(function(e) {
    e.preventDefault;

    ...open edit form and save update with $.ajax to server...
    ...with $.ajax retrieve fresh list from database...
    ...use $('#list;).html(fresh list of links)...

});

First I tried the following to "rebind" the edit link to an event:

$('.edit').on('click', function(...

That didn't work. After reading this great answer, I tried:

$(document).on('click', '.edit', function(...

and bingo! It worked.

Question: Can someone explain the differences between the two?

Thanks.

Community
  • 1
  • 1
breadwild
  • 327
  • 2
  • 4
  • 13
  • 2
    read https://learn.jquery.com/events/event-delegation/ – gaetanoM Aug 24 '16 at 17:39
  • 1
    Possible duplicate of [Should all jquery events be bound to $(document)?](http://stackoverflow.com/questions/12824549/should-all-jquery-events-be-bound-to-document) – trincot Aug 24 '16 at 17:59

1 Answers1

1

.on attach an event handler function to the selected elements. In your case, .edit to which you attached the .on is removed from DOM on your Ajax refresh and a new set of .edit elements might have injected. But the newly added .edit elements doesn't have .on attached. On the other hand, when you attached.on to parent/document level it worked fine. This is because that parent element to which you attached.on is still/always there.

Instead of document, it is always good to attach .on to the parent element - in this case #list

Developer
  • 6,240
  • 3
  • 18
  • 24