JQuery functions do not respond after adding ()

I am creating a series of div blocks that allow users to add / remove elements from each window using jQuery. I found that after adding a new element to the field, the click function associated with this element will not respond. Here's what my code looks like:

$(".add").click(function() { $("#targetbox").append("<span class='remove'>This element was added</span>"); }); $(".remove").click(function() { alert("removing"); $(this).remove(); }); 

If I pre-populate #targetbox with elements, they respond to the click function. These are only elements that are dynamically added that do not respond to the function.

+8
javascript jquery append click
source share
3 answers

Add the click method directly to your newly added item

 $(".add").click(function() { $("#targetbox").append("<span class='remove'>This element was added</span>") .bind("click",function(e) { alert("removing"); $(this).remove(); }); }); 

Or use the .live() method, which will bind the click event for you after adding any new .remove elements

 $(".add").click(function() { $("#targetbox").append("<span class='remove'>This element was added</span>"); }); $(".remove").live("click", function() { alert("removing"); $(this).remove(); }); 
+15
source share

Your code handles the click event for all items currently in $('.remove') .
Any elements that do not yet exist are not affected.

You need to call the .live() or .delegate that will handle the event for all elements matching the selector, regardless of when they were created.

For example:

 $(".remove").live('click', function() { alert("removing"); $(this).remove(); }); 
+11
source share

This is because when your code works, the elements have not yet been added. You need to add a click removal function that will be dynamically assigned to your new block after it is added during the add click function.

 $(".add").click(function() { $("#targetbox").append("<span class='remove'>This element was added</span>"); // Add code here for .remove click function }); 
+1
source share

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


All Articles