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

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

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

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

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

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

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