jQuery删除ajax成功的元素

mkt*_*ums 5 javascript jquery

我有<button>ajax,并希望在成功请求后删除它.

<script type="text/javascript">
    $(".approve").click(function(){
        var el, image_id =  $(this).data('image-id');
        $.ajax({
            type: "PATCH",
            dataType: "json",
            data: { "approved": "True"},
            url: "/ml/api/image/" + image_id + "/?format=json",
            success: function(data){
                $(this).remove();
            }
        });
    });
</script>
Run Code Online (Sandbox Code Playgroud)

但这不起作用......

Kon*_*nev 23

成功回调中的上下文与click事件的上下文不同,意味着this不再引用按钮DOM元素.只需再次选择该按钮即可将其删除:

$(".approve").click(function(){
    var el = $(this), image_id =  $(this).data('image-id');
    $.ajax({
        type: "PATCH",
        dataType: "json",
        data: { "approved": "True"},
        url: "/ml/api/image/" + image_id + "/?format=json",
        success: function(data){
            el.remove();
        }
    });
});
Run Code Online (Sandbox Code Playgroud)


Vit*_*huk 5

另一种方法是将context属性传递给ajax:

$(".approve").click(function(){
    var image_id =  $(this).data('image-id');
    $.ajax({
        context: this,
        type: "PATCH",
        dataType: "json",
        data: { "approved": "True"},
        url: "/ml/api/image/" + image_id + "/?format=json",
        success: function(data){
            $(this).remove();
        }
    });
});
Run Code Online (Sandbox Code Playgroud)