简体   繁体   English

Span addClass无法正常工作

[英]Span addClass not working ajax

I have a span like this <span class="join-event to-join">join event</span> . 我的跨度是这样的<span class="join-event to-join">join event</span> I use this function to do something with the click via AJAX. 我使用此功能通过AJAX进行点击操作。

But in the success function I can't seem to add a class to that clicked span. 但是在成功函数中,我似乎无法向该单击范围添加类。

function accept() {

    $(".to-join").click(function() {

        var id = $(this).attr("data-event");

        $.ajax({

            type: "post",
            url: "../assets/js/ajax/toggle-events.php",
            data: { 'id': id },
            success: function() {

                alert("good job");
                $(this).addClass("joined");

            },

            error: function () {

                alert("fail");

            }

        });

    });

}

Use context option of ajax method: 使用ajax方法的context选项:

context: this,

context Type: PlainObject This object will be the context of all Ajax-related callbacks. context类型:PlainObject该对象将是所有与Ajax相关的回调的上下文。 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设置($ .ajaxSettings与传递给$ .ajax的设置合并)。

You need to define $(this) as variable outside the ajax call, this inside ajax will refers to jqXHR object 您需要将$(this)定义$(this) ajax调用之外的变量,ajax内的this将引用jqXHR对象

function accept() {    
    $(".to-join").click(function() {    
        var id = $(this).attr("data-event"),
              $this=$(this);    
        $.ajax({    
            type: "post",
            url: "../assets/js/ajax/toggle-events.php",
            data: { 'id': id },
            success: function() {    
                alert("good job");
                $this.addClass("joined");    
            },    
            error: function () {    
                alert("fail");    
            }    
        });    
    });    
}
$(".to-join").click(function() {
        var span = $(this);
        var id = $(this).attr("data-event");

        $.ajax({

            type: "post",
            url: "../assets/js/ajax/toggle-events.php",
            data: { 'id': id },
            success: function() {

                alert("good job");
                span.addClass("joined");

            },

            error: function () {

                alert("fail");

            }

        });

    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM