javascript - 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内部的函数?
解决方案
将它保存到一个传统上命名为“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);
});
});
});
推荐阅读
- linux - 在 Linux 服务器上触发主机名“withsometest”时会发生什么
- python - 使用 pybind11 包装一个包含 Eigen 数组的 stl 容器(地图)
- f# - HighRise API 创建一个因缺少名字而失败的人
- dns - www.docusign.net(美国西部地区)的 DNS 解析失败
- android - 任务':app:mergeReleaseResources'构建APK的错误执行失败
- c# - 如何从 azure AD 应用程序客户端 ID 生成令牌?
- dart - 显示 Carousel Pro 中的最后一张幻灯片时如何启用“开始”按钮?
- excel - 在不使用正则表达式的情况下查找两个字符之间的数字
- sql - TSQL - 比较表中的分组值
- python - 使用 group by 检查 pandas 未来行中的条件