I am trying to change some old code which uses onclick so that I an use the $(this). The problem is that $(this) is not working when inside the success. Is there anyway to do this without setting it as a var.

$('.addToCart').click(function() {

    $.ajax({
        url: 'cart/update',
        type: 'post',
        data: 'product_id=' + $(this).attr("data-id"),
        dataType: 'json',
        success: function(json) {

            if (json['success']) {

            $(this).addClass("test");

            }   
        }
    });

});

推荐答案

问题

在回调内部,this引用Ajax调用的jqXHR对象,而不是事件处理程序绑定到的元素.Learn more about how this works in JavaScript美元.


解决

如果您可以使用ES2015+,那么使用arrow function可能是最简单的 Select :

$.ajax({
    //...
    success: (json) => {
         // `this` refers to whatever `this` refers to outside the function
    }
});

您可以设置context option:

该对象将成为所有Ajax相关回调的上下文.默认情况下,上下文是一个表示调用中使用的ajax设置的对象($.ajaxSettings与传递给$.ajax的设置合并).(...)

$.ajax({
    //...
    context: this,
    success: function(json) {
         // `this` refers to the value of `context`
    }
});

或者使用$.proxy:

$.ajax({
    //...
    success: $.proxy(function(json) {
         // `this` refers to the second argument of `$.proxy`
    }, this)
});

或者在回调之外保留对值this的引用:

var element = this;

$.ajax({
    //...
    success: function(json) {
         // `this` refers to the jQXHR object
         // use `element` to refer to the DOM element
         // or `$(element)` to refer to the jQuery object
    }
});

相关的

Jquery相关问答推荐

try 使用jQuery AJAX将参数传递给http Post方法时出现未知错误

jQuery 或 JavaScript 中的$符号是什么意思?

使用淡入淡出和追加

如何 Select 具有特定文本的所有锚标记

使用 jQuery 为 box-shadow 设置动画的正确方法

如何在数据表中显示空数据消息

如何使用 jQuery 将表格的一行滚动到视图 (element.scrollintoView) 中?

无法在被动事件侦听器中阻止默认值

在 Javascript 中,字典理解或 Object `map`

将输入更改为大写

延迟后运行功能

Jquery,清除/清空 tbody 元素的所有内容?

聚焦 时防止 iphone 默认键盘

使用 时如何从 select2 中获取选定文本

使用 jQuery 拖放防止单击事件

如何通过javascript数组中的键和值查找对象的索引

带有函数的 JavaScript 三元运算符示例

页面加载后如何执行jquery代码?

JavaScript 中的简单节流阀

为什么要定义一个匿名函数并将 jQuery 作为参数传递给它?