首页 > 解决方案 > javascript。ajax调用后如何传递“this”对象?

问题描述

我有这个代码:

$(function(){
    $("#CASA").click(function(){
        rsExecute("rs/rs_luci.php","premi",1,function(cc){});
        var col=$( this ).css( "background-color" );
        setColor(this, 'yellow');
        setTimeout(setColor,1000,this,col);
    });
});

function setColor(obj,clr){
    $(obj).css( "background-color", clr );
}

rsExecute通过 ajax 进行调用。function(cc){}成功执行。

我试图改变这样的代码:

$(function(){
    $("#CASA").click(function(){
        rsExecute("rs/rs_luci.php","premi",1,function(cc){
            var col=$( this ).css( "background-color" );
            setColor(this, 'yellow');
            setTimeout(setColor,1000,this,col);
        });
    });
});

function setColor(obj,clr){
    $(obj).css( "background-color", clr );
}

但它不起作用,因为是未定义的。

有没有办法将此对象传递给rsExecute内部的函数?

标签: javascriptjqueryajax

解决方案


将它保存到一个传统上命名为“that”的变量中,并使用闭包传递该变量。

$(function(){
    $("#CASA").click(function(){
        var that = this;
        rsExecute("rs/rs_luci.php","premi",1,function(cc){
            var col=$( that ).css( "background-color" );
            setColor(that, 'yellow');
            setTimeout(setColor,1000,that,col);
        });
    });
});

推荐阅读