這個問題在這里已經有了答案: 如何在回呼中訪問正確的“this” (13 個回答) 5 小時前關閉。
我有這個代碼:
$(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 中的函式?
uj5u.com熱心網友回復:
將它保存到一個傳統上命名為“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);
});
});
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/345972.html
標籤:javascript 查询 阿贾克斯
上一篇:使用zsh更改json檔案中的值
下一篇:`file_get_contents("php://input")`是從`fetch`獲取發布資料的唯一方法,使用異步和hack-wise是否安全?
