【问题标题】:jQuery - 'this' selector doesn't work inside callback function [duplicate]jQuery - 'this'选择器在回调函数中不起作用[重复]
【发布时间】:2012-07-14 17:48:53
【问题描述】:
可能重复:
$(this) doesn't work in a function
我正在用 jQuery 编写删除后的代码,删除本身是通过对支持的后请求进行的,在服务器返回 200 后,我想在客户端删除这篇文章。
$('.delete-post').click(function() {
$.post($(this).attr('href'), {}, function(data) {
$(this).closest('.post').remove();
});
return false;
});
但是,我注意到 function(data) {...) 内部选择器“this”不起作用。我需要使用“.post”类删除最接近$('.delete-post') div。如何管理这个问题?谢谢!
【问题讨论】:
标签:
jquery
jquery-selectors
this
【解决方案1】:
$(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();
});
});