jQuery-'this'选择器在回调函数中不起作用
可能重复:
$(this)在函数中不起作用
Possible Duplicate:
$(this) doesn't work in a function
我正在用jQuery写帖子删除代码,删除本身是通过对后备对象的后请求完成的,服务器返回200后,我想在客户端删除此帖子.
I'm writing post removing code in jQuery, The removing itself is made via post-request to backeds, after server returns 200, I want to delete this post on client-side.
$('.delete-post').click(function() {
$.post($(this).attr('href'), {}, function(data) {
$(this).closest('.post').remove();
});
return false;
});
但是,我注意到在function(data){...)内部选择器'this'不起作用.我需要使用类'.post'移除最接近$('.delete-post')
div的位置.如何解决这个问题?谢谢!
However, I've noticed that inside function(data) {...) selector 'this' doesn't work. I need to remove closest to $('.delete-post')
div with class '.post'. How to manage this problem? Thanks!
$(this)
存在于click event
中,但function(data) {
不是单击事件rather callback function
的一部分.因此,请将$(this)保存在实例that
的某个变量中,以备后用.
$(this)
exists in the click event
but function(data) {
is not part of click event rather callback function
. So save the $(this) in some variable for instance that
for later use.
尝试一下:
$('.delete-post').click(function(e) {
e.preventDefault();
var that = $(this);
$.post(that.attr('href'), { }, function(data) {
// $(this).closest('.post').remove();
that.closest('.post').remove();
});
});