Jquery add listener to added content

I have jQuery code as follows:

$("#add").click(function(event){ $("#list").append('<a class="remove" href="#">x</a>'); return false; }); $('.remove').live('click', function(){ alert("123"); }); 

If I click on the class = delete, I would like it to notify 123. However, this does not happen. I think this is a simple idea, but I am missing something.

Any ideas?

Thanks.

+4
source share
3 answers

Live is out of date, use

 $(document).on('click','.remove',function(){ alert("123"); }); 
+9
source

Another way to add an element and bind an event without delegation:

 $("#add").click(function(event){ $("<a />", { "class": "remove", href: "#", text: "x" }).on("click", function() { alert("123"); return false; }).appendTo("#list"); return false; }); 

Avoid using the live method as it is deprecated and permanently deleted in the latest version of jQuery.

+2
source

try the delegation function. Since you use this for list ... you can use #list , which is better in performance than document

  $('#list').on('click','.remove', function(){ alert("123"); }); 

you can follow the link to learn more about on () event

+1
source

All Articles