Bound events are lost when using jQuery.append

I have a simple code like this http://jsfiddle.net/9braK/2/

$(function(){

$('body').append(
    $("<a/>").attr({ "id": "foo", "href":"#" })
             .text("click me")
             .live("click",function(e){
                e.preventDefault();
                alert("Hello World!");
             })
  );
});

According to the docs this should work, right?

Answer

DOM traversal methods are not supported for finding elements to send to .live(). Rather, the .live() method should always be called directly after a selector, as in the example above.

Source

So the only problem in your code is the usage of live(). "<a/>" is not a selector, and the way live() works it won’t be able to find corresponding elements. If you simply use .click(), it will work flawlessly of course.

You can use something like

$('body')
  .append(
    $("<a/>")
      .attr({ "id": "foo", "href":"#" })
      .text("click me")
    )
  )
  .delegate("#foo", "click", function(e){
                e.preventDefault();
                alert("Hello World!");
             });

to achieve what you wanted (but I think a simple click() would be sufficient depending on your use case).

Leave a Reply

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