jQuery-'this'选择器在回调函数中不起作用 [英] jQuery - 'this' selector doesn't work inside callback function

查看:117
本文介绍了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();
    });
});

这篇关于jQuery-'this'选择器在回调函数中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆