Attemping to change attributes of $(this) inside success function

五迷三道 提交于 2019-12-12 19:13:48

问题


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

Here is my code:

$(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>

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).

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?


回答1:


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



回答2:


The $.ajax method supports passing a context property which will become the value of this inside the callback:

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



回答3:


$(this) will not availbe after ajax response. You need to make variable and store the current elm. Then triger as you need after ajax call.



来源:https://stackoverflow.com/questions/49260874/attemping-to-change-attributes-of-this-inside-success-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!