javascript jQuery删除ajax成功的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14546749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:56:20  来源:igfitidea点击:

jQuery remove element on ajax success

javascriptjquery

提问by mktums

I have <button>with ajax on it, and want to remove it after successful request.

我有<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>

But this doesn't work…

但这不起作用……

回答by Konstantin Dinev

The context in the success callback is different from the context of the click event meaning thisno longer refers to the button DOM element. Just select the button again and it would remove it:

成功回调中的上下文与单击事件的上下文不同,这意味着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();
        }
    });
});

回答by Vitalii Petrychuk

Another way is to pass contextproperty to ajax:

另一种方法是将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();
        }
    });
});

回答by Pierre Brzezny

This is my methode. Easy.

这是我的方法。简单。

var element = $(this);

 $.ajax({
     success: function(){          
          element.remove();     
     }
});