简体   繁体   English

在AJAX函数中.remove()不起作用

[英]In AJAX Function .remove() not working

In a jQuery click function using $.post() I have a .remove() function nested within the response function if the response returns true. 在使用$.post()的jQuery click函数中,如果响应返回true,则在响应函数中嵌套有一个.remove()函数。 My alert() appears to work correctly with the code is processed, however the .remove() does not seem to work whatsoever even though the alert() code in the same space appears to process. 我的alert()似乎可以正确处理代码,但是.remove()似乎不起作用,即使似乎在同一空间中的alert()代码也可以处理。 The same code when placed outside of $.post() works just fine. 将相同的代码放在$.post()之外时,效果很好。

var container = $(".container");
var delete = $("a.delete");
var dataId = $(delete).data("dataid");

delete.click(function(e) {
    e.preventDefault();
    $.post("url.php",
        {'data': dataId},
        function(response) {
            if (response == true) {
                alert("IT WORKED");
                $(this).closest(container).remove();
            }
        },
        "json"
    );
});

Make the following change and it should work. 进行以下更改,它应该可以工作。 In the success callback this is the jqXHR object, therefore you have to cache this before the ajax call: 在成功回调thisjqXHR对象,所以你必须缓存this Ajax调用之前:

delete.click(function(e) {
    e.preventDefault();
    var that = $(this);
    $.post("url.php",
        {'data': dataId},
        function(response) {
            if (response == true) {
                alert("IT WORKED");
                that.closest(container).remove();
            }
        },
        "json"
    );
});

As an alternative to the other answer, one could also use the jQuery.proxy() function to associate the context with what you might desire. 作为其他答案的替代方法,也可以使用jQuery.proxy()函数将上下文与您所需的内容相关联。

For example: 例如:

delete.click(function(e) {
    e.preventDefault();
    $.post("url.php",
        {'data': dataId},
        $.proxy(function(response) {
            if (response == true) {
                alert("IT WORKED");
                $(this).closest(container).remove();
            }
        }, this),
        "json"
    );
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM