为了账号安全,请及时绑定邮箱和手机立即绑定

AJAX成功内部的$(这个)不起作用

AJAX成功内部的$(这个)不起作用

米脂 2019-06-09 16:53:31
AJAX成功内部的$(这个)不起作用我正在尝试更改一些使用onClick的旧代码,这样我就可以使用$(This)。问题是,在成功的内部,$(这个)是不起作用的。在不将其设置为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");             }            }     });});
查看完整描述

2 回答

?
料青山看我应如是

TA贡献1772条经验 获得超7个赞

问题

在回调内部,this指的是jqXHR对象,而不是事件处理程序绑定到的元素。了解更多关于如何this在JavaScript中工作.


如果ES 2015+对您可用,则使用箭头函数可能是最简单的选择:

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

您可以设置context期权:

这个对象将成为所有与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
    }});

相关


查看完整回答
反对 回复 2019-06-09
?
弑天下

TA贡献1818条经验 获得超7个赞

jQuery(".custom-filter-options .sbHolder ul li a").each(function () {
    var myStr = jQuery(this).text();
    var myArr = myStr.split(" (");
     url = 'your url'; // New Code
            data = myArr[0];
                try {
                    jQuery.ajax({
                        url : url,
                        context: this,
                        type : 'post',
                        data : data,
                        success : function(data) {
            if(data){
                  jQuery(this).html(data);
            }else{
                  jQuery(this).html(myArr[0]);
            }
                        }
                    });
                } catch (e) {
                } });


查看完整回答
反对 回复 2019-06-09
  • 2 回答
  • 0 关注
  • 883 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信