0

I am appendend a hyperlink to the html page using append() method, It is a list of hyperlinks, and I get all other elements id by this.id, but am not able for the appended row, why this happening? is there any other way to append ??

thanks in advance

user3017713
  • 75
  • 1
  • 10

1 Answers1

0

It sounds like somewhere in your code you have this:

$("selector for links").on("click", function() {
    // Using this.id here
    return false; // Since they're links I assume you do this or e.preventDefault();
});

and after that code runs, you add another link, but clicking it doesn't trigger the handler above. That's because the code above hooks the event on the elements that exist as of when it runs; since the link you add didn't exist, its click event didn't get hooked.

You can use event delegation to solve this, by changing the code above to:

$("selector for container").on("click", "selector for links", function() {
    // Using this.id here
    return false;
});

That hooks click on a container that holds the links, but fires the handler as though the event had been hooked on individual links. So since the event is hooked on the container, you get the event even when you add new links.

Concrete example:

$(document).on("click", "a", function() {
    alert(this.id);
    return false;
});
T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
  • I suspect this is the right answer. I've been trying to get him to clarify, because then I could just close this question as a duplicate of http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – Barmar Aug 23 '14 at 07:37