JQuery - the 'this' selector does not work inside the callback function

Possible duplicate:
$ (this) does not work in function

I write the deletion postcode in jQuery, the deletion itself is done through the post-request for backeds, after the server returns 200, I want to delete this message on the client side.

$('.delete-post').click(function() { $.post($(this).attr('href'), {}, function(data) { $(this).closest('.post').remove(); }); return false; }); 

However, I noticed that inside the function (data) {...) the 'this' selector does not work. I need to remove the closest to $('.delete-post') div with class '.post'. How to deal with this problem? Thanks!

+6
source share
1 answer

$(this) exists in click event , but function(data) { not part of the click event rather callback function . Therefore, save $ (this) in some variable, such as that for future reference.

Try the following:

 $('.delete-post').click(function(e) { e.preventDefault(); var that = $(this); $.post(that.attr('href'), { }, function(data) { // $(this).closest('.post').remove(); that.closest('.post').remove(); }); }); 
+11
source

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


All Articles