javascript – jQuery how to bind onclick event to dynamically added HTML element

javascript – jQuery how to bind onclick event to dynamically added HTML element

All of these methods are deprecated. You should use the on method to solve your problem.

If you want to target a dynamically added element youll have to use

$(document).on(click, selector-to-your-element , function() {
     //code here ....
});

this replace the deprecated .live() method.

The first problem is that when you call append on a jQuery set with more than one element, a clone of the element to append is created for each and thus the attached event observer is lost.

An alternative way to do it would be to create the link for each element:

function handler() { alert(hello); }
$(.add_to_this).append(function() {
  return $(<a>Click here</a>).click(handler);
})

Another potential problem might be that the event observer is attached before the element has been added to the DOM. Im not sure if this has anything to say, but I think the behavior might be considered undetermined.
A more solid approach would probably be:

function handler() { alert(hello); }
$(.add_to_this).each(function() {
  var link = $(<a>Click here</a>);
  $(this).append(link);
  link.click(handler);
});

javascript – jQuery how to bind onclick event to dynamically added HTML element

How about the Live method?

$(.add_to_this a).live(click, function() {
    alert(hello from binded function call);
});

Still, what you did about looks like it should work. Theres another post that looks pretty similar.

Leave a Reply

Your email address will not be published. Required fields are marked *