jQuery fadeOut回调错误

jQuery fadeOut callback error

本文关键字:错误 回调 fadeOut jQuery      更新时间:2023-09-26

Firebug表示我有一个TypeError: a.ownerDocument is undefined,代码为:

$(this).text('Updated!').fadeOut('900',  function() { 
  $(this).text('Update').attr('disabled', 'disabled').show()
});

下面是一个更完整的片段:

$(".update-role").click(function() {
  var newRole = $(this).prev().val();
  var userId  = $(this).parents('tr').attr('id');  // e.g. 'user-role-18'
  userId = userId.split('-');
  userId = userId[2]; // so we get '18'
  $.getJSON('services/update_staff_role.php', {r: newRole, id: userId}, function(j) {
    if(j.result == 'success') {
    $(this).text('Updated!').fadeOut('900',  function() { 
          $(this).text('Update').attr('disabled', 'disabled').show()
        });
    } else {
      alert(j.reason);
    }
  });
  console.info(userId, newRole);
});

可能是因为我在使用this,还是因为我在另一个callback中使用callback

添加var _this = $(this);,然后使用_this.text...而不是$(this).text..,因为$(this)指的是$.getJSON:

$(".update-role").click(function() {
  var _this = $(this);
  var newRole = $(this).prev().val();
  var userId  = $(this).parents('tr').attr('id');
  userId = userId.split('-');
  userId = userId[2];
  $.getJSON('services/update_staff_role.php', {r: newRole, id: userId}, function(j) {
    if(j.result == 'success') {
    _this.text('Updated!').fadeOut('900',  function() { 
          $(this).text('Update').attr('disabled', 'disabled').show()
        });
    } else {
      alert(j.reason);
    }
  });
  console.info(userId, newRole);
});

是的,this在回调中不是指单击的按钮。在调用$.getJSON之前,您可以将按钮引用存储在一个变量中,然后在回调中访问该变量。