jQuery点击传递(this)到ajax成功函数

时间:2015-11-30 18:19:19

标签: javascript jquery ajax

我做了一些研究,但很少有类似的问题,但没有解决我的问题。

我在报告中对记录进行Ajax调用,我通过Ajax设置/删除标记。

的jQuery

jQuery('.flag').click(function(){  
    if(jQuery(this).hasClass('active_flag')){
        // REMOVE Record
        jQuery.ajax({
            url: '/flag/remove',
            type: "post",
            data: { '_method' : 'delete',
                    'timeRecordID':jQuery(this).attr('data-record'), 
                    '_token':  '{!! csrf_token() !!}' 
                    },
            success: function(data){
                jQuery(this).removeClass('active_flag'); // (this) doesn't refer to same (this) inside the click function
            }
        });
    }

我也尝试过这个链接StackOverflow的解决方案,但这并没有解决我的问题。

感谢您的帮助

2 个答案:

答案 0 :(得分:5)

首先定义$(this)

jQuery('.flag').click(function(){  
        var ThisIt = $(this); //<<<<<<<<<<<<<<<<<<<<<<<<
        if(ThisIt.hasClass('active_flag')){

            // REMOVE Record
            jQuery.ajax({
                url: '/flag/remove',
                type: "post",
                data: { '_method' : 'delete',
                        'timeRecordID': ThisIt.attr('data-record'), 
                        '_token':  '{!! csrf_token() !!}' 
                        },
                success: function(data){
                    ThisIt.removeClass('active_flag'); // (this) doesn't refer to same (this) inside the click function
                }
            });

        }
});

答案 1 :(得分:3)

使用.bind按顺序获取this

success: function(data){
    jQuery(this).removeClass('active_flag');
}.bind(this)

之后阅读.bind here

的内容