Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 试图在成功函数内更改$(this)的属性_Javascript_Jquery_Font Awesome - Fatal编程技术网

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

Javascript 试图在成功函数内更改$(this)的属性,javascript,jquery,font-awesome,Javascript,Jquery,Font Awesome,我正在尝试根据单击上一个图标的结果更改图标 这是我的密码: $(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',

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

这是我的密码:

$(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="<?=$task['uid'];?>" class="far fa-square fa-lg switchButton"></i>
该方法支持传递一个
上下文
属性,该属性将成为回调中此
的值:

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

在$.ajax调用之前,通过
const=this
保存
this
上下文。然后在
success()
中使用
that
而不是
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响应后将不可用。您需要创建变量并存储当前elm。然后在ajax调用后根据需要触发。

没有必要-jQuery可以为您执行此操作,或者如果您喜欢变量-
var$this=$(this)
@Alnitak-true但定义此外部意味着在整个函数中使用,而不仅仅是在ajax中使用call@ThisGuyHasTwoThumbs这是另一个问题。OP特别想要
success
回调中的上下文。您的
$this=$(this)
that=this
更可取。@Alnitak是的,该方法有办法做到这一点,但这种方法也有效。没有理由为此而生气。无论哪种方式,它实际上只是代码中的一行差异。如果用户希望使用箭头函数进行回调,这种方法也会起作用。如果在回调中使用
console.log(this)
,会得到什么?当我这样做时,我会得到编辑之前的元素。在属性更改之前,我有日志。这是返回:(将其放在pastebin上,因为注释中的格式设置看起来很混乱)您的问题在别处,很可能与您在此处提出的特定问题无关(即如何使回调中的
引用正确的元素)