After append (), how to associate the click event with the added item

I have this code

$(".delete2").click(function() { $('#load2').fadeIn(); } 

I have dynamically added an item using this return

 addSubcategory = function(){ sucategorynameval = $("#sucategoryname").val(); categoryId = $("#addcategoryid").val(); $.get("process-add-subcat.php", { "action": "add_subcategory", "sucategoryname": sucategorynameval, "categoryId":categoryId }, function(data){ //$("#main-cat-"+categoryId).load(location.href+"&pageExclusive=1 #main-cat-"+categoryId+">*",""); $("#main-cat-"+categoryId).append(data); $("#addcategoryid").val(''); $("#sucategoryname").val(''); }); 

The returned data contains delete2 classified element.

How to apply click event to newly added item?

+4
source share
3 answers

Ok, you can just double-check it with the same click function you used before, or use .live () http://api.jquery.com/live/

+3
source

Replace

 $(".delete2").click(function() { $('#load2').fadeIn(); } 

from

 $(".delete2").live('click', function() { $('#load2').fadeIn(); }); 

Thus, the click event is bound to all existing a in future created elements with class .delete2

+2
source
 $(<parent selector>).on('click', '.delete2', function() { alert('test'); }); 

Change parent selector to id or parent element class

+1
source

Source: https://habr.com/ru/post/1304310/


All Articles