$(this) 内部 AJAX 成功不起作用 [英] $(this) inside of AJAX success not working

查看:28
本文介绍了$(this) 内部 AJAX 成功不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更改一些使用 onclick 的旧代码,以便我使用 $(this).问题是 $(this) 在成功时不起作用.有没有办法在不将其设置为 var 的情况下执行此操作.

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 对象,而不是事件处理程序绑定到的元素.详细了解this的工作原理在 JavaScript 中.

Problem

Inside the callback, this refers to the jqXHR object of the Ajax call, not the element the event handler was bound to. Learn more about how this works in JavaScript.

如果您可以使用 ES2015+,那么使用箭头函数可能是最简单的选择:

If ES2015+ is available to you, then using an arrow function would probably be the simplest option:

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

您可以设置context 选项:

You can set the context option:

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

This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.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的值的引用:

or keep a reference to the value of this outside the callback:

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
    }
});

<小时>

相关

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