试图在成功函数内更改$(this)的属性 [英] Attemping to change attributes of $(this) inside success function

查看:44
本文介绍了试图在成功函数内更改$(this)的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm attempting to change an icon based on a result from clicking on the previous icon.

这是我的代码:

$(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');
            }
        }
    });
});

该图标最初位于页面上:

The icon is initially on the page by:

<i data-uid="<?=$task['uid'];?>" class="far fa-square fa-lg switchButton"></i>

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

When a user clicks this icon, an ajax request is sent to a php script that will update a boolean variable in a table, and return the truthy value of if the boolean is true or not (0 or 1).

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

When the icon is clicked initially, the icon is switched to a spinner icon which is done by the first like mentioning $(this), once the request gets to the success function, it should change the icon again based on the response given, but it does not work. There is simply no update to the page. I assume this is is a scope issue, but reading various articles about this and doing some research I haven't been able to find a way to fix it. It certainly doesn't help that I don't actually know if it is a scope issue or not.

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

how can I update these icons inside the success function?

推荐答案

通过 const保存上下文=这个在$ .ajax调用之前。然后在 success()里面只使用那个而不是这个

Save the this context by const that = this before $.ajax call. Then inside the success() just use that instead of 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');
        }
    }
  });
});

这篇关于试图在成功函数内更改$(this)的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆