转: jquery中ajax回调函数使用this

时间:2025-05-11 12:36:15

原文地址:jquery中ajax回调函数使用this

写ajax请求的时候success中代码老是不能正常执行,找了半天原因。代码如下

 $.ajax({type: 'GET',
url: "/flag/",
data: dat,
success:function(){
$(this).prevAll('p').css("text-decoration","line-through");
}
});

最后发现是ajax中的回调函数(success等)直接用this不灵,解决办法是使用bind(this)绑定this到当前事件。

 $.ajax({type: 'GET',
url: "/flag/",
data: dat,
success:function(){
$(this).prevAll('p').css("text-decoration","line-through");
}.bind(this)
});

---------------------
作者:Lius153
来源:****
原文:https://blog.****.net/Lius153/article/details/70145529
版权声明:本文为博主原创文章,转载请附上博文链接!