0

I have dynamically created element

<a class="update-link">

with path: body > div#MySection > table> tbody > tr > td > div > a.update-link.

When I bind event using

$(document).on("click", ".update-link", fn) 

The event is triggered.

When I use $("body") or $("#MySection"), the event is not triggered. $(document) works but is inefficient due to the large scope. Why don't the more specific selectors work?

Ele
  • 33,468
  • 7
  • 37
  • 75
ferk86
  • 2,325
  • 1
  • 23
  • 27

1 Answers1

0

You can pass a context through with your event delegation:

$(() => {
  $(document, ".sec", "button").on("click", () => {
    console.log("clicked");
  });
  
  $(".sec").append("<button>Test</button>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<section class="sec"></section>

So in your case, .sec would be body or #MySection.

Zze
  • 18,229
  • 13
  • 85
  • 118