试图在成功函数内更改$(this)的属性

我正在尝试根据点击上一个图标的结果更改图标。

这是我的代码:

$(document).on('click','.switchButton', function(){ $(this).attr('data-prefix', 'fas').attr('data-icon', 'spinner').addClass('fa-pulse'); $.ajax({ url: 'tasks/update_table.php', type: 'post', data: { "uid": $(this).attr('data-uid')}, success: function(response) { if(response == 1) { $(this).attr('data-prefix', 'far').attr('data-icon', 'check-square'); } else { $(this).attr('data-prefix', 'fas').attr('data-icon', 'check-square'); } } }); }); 

该图标最初位于页面上:

 <i data-uid="" class="far fa-square fa-lg switchButton"> 

当用户单击此图标时,会向php脚本发送ajax请求,该脚本将更新表中的布尔变量,如果布尔值为true(0或1),则返回truthy值。

当最初点击图标时,图标会切换到一个微调器图标,这个图标由第一个完成,如提到$(this) ,一旦请求到达成功函数,它应该根据给出的响应再次更改图标,但是这是行不通的。 页面根本没有更新。 我认为这是一个范围问题,但阅读有关此问题的各种文章并进行一些研究我还没有找到解决方法。 我实际上并不知道它是否是范围问题当然没有帮助。

如何在成功function中更新这些图标?

在$ .ajax调用之前,使用const that = this保存this上下文。 然后在success()内部使用而不是this

 $(document).on('click','.switchButton', function(){ $(this).attr('data-prefix', 'fas').attr('data-icon', 'spinner').addClass('fa-pulse'); const that = this; // save $.ajax({ url: 'tasks/update_table.php', type: 'post', data: { "uid": $(this).attr('data-uid')}, success: function(response) { if(response == 1) { $(that).attr('data-prefix', 'far').attr('data-icon', 'check-square'); } else { $(that).attr('data-prefix', 'fas').attr('data-icon', 'check-square'); } } }); }); 

$.ajax方法支持传递一个context属性,该属性将成为回调内部的值:

 $.ajax({ context: this, success: function(response) { // this === context here }, ... }); 

在ajax响应之后,$(this)将无法获得。 您需要创建变量并存储当前的elm。 然后在ajax调用后根据需要进行调整。