Ajax(这个)不起作用

Ado*_*ola 7 html javascript ajax jquery

当试图访问$ container的'.box'类时,在ajax调用中使用(this)不起作用.

$container.on(
        "click",
        ".box",
        function(event){
            var description;
            if($(this)[0].style.width == '70%'){
                $(this).find(".resultData").fadeOut('slow');
                $(this).css('width', '18%');
            }else{
                $.ajax({
                    url:'scripts/php/fetchResultsData.php',
                    data: {action:value},
                    type: 'post',
                    dataType: 'json',
                    success: function(data){
                        description = data[0];
                        $(this).css('width', '70%');
                        $(this).append("\
                            <div class='resultData'>\
                                <div class='resultName'>" + $(this).find("p").html() + "</div>\
                                <div class='resultDesc'>" + description +"</div>\
                            </div>");
                        /*alert($(this).find("p").html());*/
                    }
                    })
            }
            $container.masonry('reload');
        }
    );
Run Code Online (Sandbox Code Playgroud)

如果我不清楚我想要做什么,我试图改变动态元素的CSS.但是,例如,

$(this).css('width','70%');

根本没有调整css.如果我将它移到ajax,success部分之外,它可以工作,但是我无法获得'描述'.

Bis*_*opZ 13

你很亲密 在您使用它的上下文中,"this"指的是ajax请求,而不是发出事件的事物.要解决此问题,请在发出ajax请求之前存储此副本:

                   }else{
                        var me = this;
                        $.ajax({
                            ...
                            success: function(data){
                                description = data[0];
                                $(me).css('width', '70%');
Run Code Online (Sandbox Code Playgroud)


小智 10

只需将此添加到您的$.ajax通话中......

context: this,
Run Code Online (Sandbox Code Playgroud)

......它会起作用.


$.ajax({
    context: this, // <-- right here
    url:'scripts/php/fetchResultsData.php',
    data: {action:value},
    type: 'post',
    dataType: 'json',
    success: function(data) { // ...
Run Code Online (Sandbox Code Playgroud)