Dynamically added class cannot be called

I am trying to perform a deletion on a page that is populated with data using an ajax call. my page has this before loading the data:

<span id="ShowSelectedCategories"></span> 

and after ajax call I fill in the following information:

 function(data){ $('#ShowSelectedCategories').prepend('<a href="" id="'+b.SelectedCategoriesID+'" class="DeleteCat"> x <span style="color:red">' + data +'</span> </a>&nbsp '); } 

and finally, after clicking the "I want to delete an item with a click" button, but it does not work.

 $(function(){ $("#ShowSelectedCategories").click(function(e){ e.target.outerHTML //this is the part i want to remove after click e.preventDefault(); }) 

I tried $(".DeleteCat).click() , but it gave an error because elements with this class were created dynamically.

Your help is appreciated.

+4
source share
3 answers
 $('#ShowSelectedCategories').on('click', '.DeleteCat', function(e){ $(this).remove(); e.preventDefault(); }); 

http://jsfiddle.net/Dj5NQ/

+2
source

Try $(e.target).remove() ,

 $("#ShowSelectedCategories").click(function(e){ $(e.target).remove(); e.preventDefault(); }); 

If you want to delete an element with class DeleteCat within the span with id ShowSelectedCategories, you can do this as follows:

 $("#ShowSelectedCategories").on("click", "DeleteCat" function(e){ $(this).remove(); e.preventDefault(); }); 
+5
source

Use something like this to call a dynamically added class

 $('.class').live("click", function(){ $('#id').remove(); }); 
+1
source

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


All Articles