JQUERY AJAX-成功时更改$(this)的类 [英] JQUERY AJAX - change class of $(this) in case of success

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

问题描述

我有一个div.在那个div中,我有多个元素.一些元素具有类"myClass".我也有一个按钮.单击时,将对div中具有类myClass的每个元素运行一个foreach循环.将为每个元素发送一个ajaxCall.这些元素的文本颜色默认为黑色.如果成功完成ajax调用.我想删除类classBlackFont并添加一个类GreenFont.我尝试了以下代码,尽管ajax调用成功了,但是不幸的是,这些代码仍未切换类.

I have a div. Inside that div I have multiple elements. Some elements have the class 'myClass'. I also have a button. When clicked, a foreach loop runs for each element that has the class myClass within the div. An ajaxCall is send for each element. The text color of those elements are black by default. In case of success of the ajax call. I would like to remove the class classBlackFont and add the one classGreenFont. I tried the following code which is unfortunately not switching the classes eventhough the ajax call succeeded.

$("#someDiv .myClass").each(function() {

    var ajaxData = "myAjaxData";
    $.ajax({
        type: "POST",
        url: "somefile.php",
        data: ajaxData,
        success: function(data) {

            $(this).removeClass('classBlackFont').addClass('classGreenFont');
        }
    });

});​

推荐答案

this并非自动引用ajax回调中的正确对象.您可以通过关闭确实具有正确值的变量来更改该值:

this is not automatically a reference to the right object in the ajax callback. You can change that by closing over a variable that does have the right value:

$("#someDiv .myClass").each(function() {
    var $this = $(this);
    var ajaxData = "myAjaxData";
    $.ajax({
        type: "POST",
        url: "somefile.php",
        data: ajaxData,
        success: function(data) {
            $this.removeClass('classBlackFont').addClass('classGreenFont');
        }
    });

});​

或使用$.ajax() context选项:

$("#someDiv .myClass").each(function() {
    var ajaxData = "myAjaxData";
    $.ajax({
        type: "POST",
        url: "somefile.php",
        data: ajaxData,
        context: this,
        success: function(data) {
            $(this).removeClass('classBlackFont').addClass('classGreenFont');
        }
    });

});​

这篇关于JQUERY AJAX-成功时更改$(this)的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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