JavaScript中如何向AJAX接口rsExecute的成功回调函数传递this对象
解决方案
问题本质是普通函数作为异步回调被调用时,this不会继承外层点击事件回调的上下文,指向发生了偏移。你可以通过以下几种方式解决:
方法1:提前缓存this引用
在点击回调的最外层将目标元素的this存为变量,回调内直接访问该变量即可,兼容性最好:
$(function(){ $("#CASA").click(function(){ // 提前缓存this指向的当前点击元素 const self = this; rsExecute("rs/rs_luci.php","premi",1,function(cc){ var col=$( self ).css( "background-color" ); setColor(self, 'yellow'); setTimeout(setColor,1000,self,col); }); }); }); function setColor(obj,clr){ $(obj).css( "background-color", clr ); }
方法2:使用箭头函数作为回调
ES6箭头函数没有独立的this,会继承外层作用域的this指向,不需要额外缓存变量:
$(function(){ $("#CASA").click(function(){ // 把普通回调改成箭头函数 rsExecute("rs/rs_luci.php","premi",1, (cc) => { var col=$( this ).css( "background-color" ); setColor(this, 'yellow'); setTimeout(setColor,1000,this,col); }); }); }); function setColor(obj,clr){ $(obj).css( "background-color", clr ); }
方法3:用bind绑定回调的this指向
通过Function.prototype.bind手动将回调函数的this绑定为外层点击事件的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); }.bind(this)); // 绑定外层this }); }); function setColor(obj,clr){ $(obj).css( "background-color", clr ); }
内容的提问来源于stack exchange,提问作者Atman
相关产品推荐
相关产品推荐

