【问题标题】: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();
        });
    });
    

    【讨论】:

    • 你应该解释为什么this在回调中有不同的值。
    • 我已经解释过了谢谢你提醒我@jfriend00
    • 非常感谢,我知道了!简单明了)
    猜你喜欢
    • 2016-02-01
    • 2018-06-16
    • 2020-05-29
    • 1970-01-01
    • 2015-02-09
    • 2017-06-24
    • 2020-03-08
    相关资源
    最近更新 更多