1

您好,我编写了一个代码,需要在 ajax 调用之后添加一个类。我确信代码是正确的,但仍然没有添加类。这真的很奇怪,因为代码中的所有其他内容都有效,我确信 addClass 的代码是正确的,我也检查了控制台是否有任何错误,但没有错误。这是我的代码

$(document).on('click', '.miclickks', function(event) {
 event.preventDefault();

var for_uid    = $(this).parents("li").attr('data');
var for_name   = $(this).parents("li").attr('unme');
var for_pic    = $(this).parents("li").attr('upic');
var owner_uid  = $('.row-fluid').attr('uid');
var owner_name = $('.row-fluid').attr('usnm');
var owner_pic  = $('.row-fluid').attr('usp');
var type       = "kiss";

var dataString = "type=" + type + "&for_uid=" + for_uid + "&for_name=" + for_name + "&for_pic=" + for_pic + "&owner_uid=" + owner_uid + "&owner_pic=" + owner_pic + "&owner_name=" + owner_name; 

        $.ajax({
            type: "POST",
            url: "include/ajax.php",
            data: dataString,
            success: function (html) {
            if(html=="300")
            {
            $('#myModal .modal-body p').html("Error Please Try Again.");

            $('#myModal').modal('show');
            }
            else
            {
            $(this).addClass('active');     


            }
            }
        });



});
4

4 回答 4

6

两种方式:

首先

var that = this;
$.ajax({
    type: "POST",
    url: "include/ajax.php",
    data: dataString,
    success: function (html) {
        if (html == "300") {
            $('#myModal .modal-body p').html("Error Please Try Again.");
            $('#myModal').modal('show');
        } else {
            $(that).addClass('active');
        }
    }
});

第二(使用context选项):

$.ajax({
    type: "POST",
    url: "include/ajax.php",
    data: dataString,
    context: this,
    success: function (html) {
        if (html == "300") {
            $('#myModal .modal-body p').html("Error Please Try Again.");
            $('#myModal').modal('show');
        } else {
            $(this).addClass('active');
        }
    }
});
于 2013-05-19T11:38:06.420 回答
2

尝试这个 -

var $p = $(this);
$.ajax({
    type: "POST",
    url: "include/ajax.php",
    data: dataString,
    success: function (html) {
        if (html == "300") {
            $('#myModal .modal-body p').html("Error Please Try Again.");

            $('#myModal').modal('show');
        } else {
            $p.addClass('active');
        }
    }
});
于 2013-05-19T11:37:00.413 回答
1

原因是this里面success()是 XHR 对象而不是点击的元素。您可以使用该context选项将其强制为您想要的任何值。

例如:

$.ajax({
    context: this, // pass the clicked element via context
    ...
    success: function() {
       ...
       $(this).addClass('active'); // now this refers to the clicked element
    }
});
于 2013-05-19T11:39:09.060 回答
0

也许我说错了,有人会纠正,但我认为错误出在这条指令中:$(this).addClass('active'); 在这种情况下,“this”指的是 ajax 对象,所以请确保您正在调用添加类的正确对象积极的

于 2013-05-19T11:38:52.450 回答