jQuery在ajax成功时删除元素 [英] jQuery remove element on ajax success

查看:114
本文介绍了jQuery在ajax成功时删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的<button>上带有ajax,并希望在成功请求后将其删除.

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

<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…

推荐答案

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

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

$(".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();
        }
    });
});

这篇关于jQuery在ajax成功时删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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