0

I get the id of a li that was clicked like this:

        $("#repository-tabs li").on("click", function(e) {
            alert(this.id);
        });

Easy, problem is, I add li elements dynamically afterwards:

        $("#add-tab").click(function() {
            tabs = $("#repository-tabs li").length - 1;
            append_at = tabs - 2;
            $("#repository-tabs li:eq(" + append_at + ")").after('<li id="repository-tab-' + tabs + '" class="tab col s3 z-depth-5"><a class="white green-text text-darken-2 waves-effect waves-light" href="javascript:void(0);">Repositório ' + tabs + '</a></li>');
        });

Now, when I click the added li elements, no event is triggered. So, how can I get the ID of a future clicked item?

Ericson Willians
  • 7,606
  • 11
  • 63
  • 114

1 Answers1

1

Don't apply the event directly to the tab element; instead, apply it to the parent and delegate it.

on() has a second optional parameter, selector, to filter the descendants of the selected elements that trigger the event.

$("#repository-tabs").on("click", "li", function() {
  alert(this.id);
});

From the docs:

Delegated event handlers have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers

David
  • 6,695
  • 3
  • 29
  • 46