【问题标题】:javascript. How to pass the "this" object after ajax call? [duplicate]javascript。 ajax调用后如何传递“this”对象? [复制]
【发布时间】:2021-11-02 21:54:21
【问题描述】:

我有这个代码:

$(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 );
}

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

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

【问题讨论】:

标签: javascript jquery ajax


【解决方案1】:

将其保存到一个传统上命名为“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);
        });
    });
});

【讨论】:

  • 这是十多年前最好的方法。今天有更好的选择:(cc) => {}function(cc){}.bind(this)。但是所有这些都已经在 Stack Overflow 上第四个最常链接的 JS 问题中提出了。
  • 同意,这使用了 OP 在原始 sn-p 中的相同约定。
猜你喜欢
  • 2014-09-02
  • 1970-01-01
  • 2013-01-01
  • 2015-12-02
  • 1970-01-01
  • 1970-01-01
  • 2012-04-25
  • 2016-09-21
  • 1970-01-01
相关资源
最近更新 更多