2012-07-15 81 views
6

可能重复:
$(this) doesn't work in a functionjQuery的 - “这个”选择不回调函数里面工作

我写帖子jQuery中移除代码,除去本身是通过由请求服务器返回200后,我想在客户端删除此帖子。

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

但是,我注意到里面的函数(数据){...)选择器'这'不起作用。我需要删除最接近$('.delete-post') div类“.post”。如何管理这个问题?谢谢!

回答

10

$(this)存在于click event中,但function(data) {不是单击事件rather callback function的一部分。因此,将$(this)保存在一些变量中,例如that以备后用。

试试这个:

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

你应该解释为什么'this'有回调不同的值。 – jfriend00 2012-07-15 19:21:22

+0

我已经解释了谢谢你提醒我@ jfriend00 – Adil 2012-07-15 19:22:17

+0

非常感谢你,现在我明白了!简单明了) – f1nn 2012-07-15 19:25:35