jQuery选择器$(此)未按预期工作

jQuery选择器$(此)未按预期工作,jquery,Jquery,提交ajax请求时,我希望在发送前切换类,在出错时切换回类,或者在一切正常时保留类。但是$(这个)选择器似乎不起作用,我不知道为什么。我正在使用jquery1.4.3 html this默认情况下是指ajax对象本身,如果希望this成为特定的对象,请使用设置回调中的this内容,如下所示: $('.vote-down').click(function() { var voteData = '&postId=' + $(this).data('postId') +

提交ajax请求时,我希望在发送前切换类,在出错时切换回类,或者在一切正常时保留类。但是
$(这个)
选择器似乎不起作用,我不知道为什么。我正在使用jquery1.4.3

html


this
默认情况下是指
ajax
对象本身,如果希望
this
成为特定的对象,请使用设置回调中的
this
内容,如下所示:

$('.vote-down').click(function() {
  var voteData = '&postId=' + $(this).data('postId') + 
                 '&voteId=' + $(this).data('voteid');
  $.ajax({
     context: this,
     dataType: 'script',
     url: "myURL" + "?format=js" + voteData,
     error: function() { $(this).toggleClass("status-3"); },
     beforeSend: function() { $(this).toggleClass("status-3"); }
  });
  return false;
}); 

我删除函数参数只是为了清理,如果不使用它们,就不需要它们。

默认情况下是指
ajax
对象本身,如果希望
是特定的,请使用设置回调中的
内容,如下所示:

$('.vote-down').click(function() {
  var voteData = '&postId=' + $(this).data('postId') + 
                 '&voteId=' + $(this).data('voteid');
  $.ajax({
     context: this,
     dataType: 'script',
     url: "myURL" + "?format=js" + voteData,
     error: function() { $(this).toggleClass("status-3"); },
     beforeSend: function() { $(this).toggleClass("status-3"); }
  });
  return false;
}); 

我删除函数参数只是为了清理,如果不使用它们,就不需要它们。

常见错误<代码>此指的是XHR请求,而不是元素:

$('.vote-down').click(function() {
  var that = this; // save a reference to the element;

  $.ajax({
    dataType: 'script',
    url: "myURL" + "?format=js" + voteData,
    error: function() {
      $(that).toggleClass("status-3");
    },
    beforeSend: function() { 
      $(that).toggleClass("status-3");
    }
  });

  return false;
});

这是因为jQuery像这样调用error和beforeSend函数:
userfunction.apply(xhr[,args])
,这使得
这个
关键字引用XHR。

常见错误<代码>此指的是XHR请求,而不是元素:

$('.vote-down').click(function() {
  var that = this; // save a reference to the element;

  $.ajax({
    dataType: 'script',
    url: "myURL" + "?format=js" + voteData,
    error: function() {
      $(that).toggleClass("status-3");
    },
    beforeSend: function() { 
      $(that).toggleClass("status-3");
    }
  });

  return false;
});

这是因为jQuery像这样调用error和beforeSend函数:
userfunction.apply(xhr[,args])
,这使得
this
关键字引用XHR。

选项中有一个属性;)为了准确起见,它们不是这样调用的,例如使用
call
调用
beforeSend
调用
s.beforeSend.call(s.context,xhr,s)
s.context
默认为设置对象本身,如果没有设置)。选项中有一个属性;)为了准确起见,它们不是这样调用的,例如使用
call
调用
beforeSend
调用
s.beforeSend.call(s.context,xhr,s)
s.context
如果未设置,则默认为设置对象本身).+1我认为
context
属性可能是鲜为人知的功能之一。+1我认为
context
属性可能是鲜为人知的功能之一。仅供参考,您可能希望升级到
1.4.4
,因为这样做可以避免许多错误(与此处的问题无关)。谢谢Patrick!我会的。仅供参考,您可能需要升级到
1.4.4
,因为这样做可以避免许多错误(与此处的问题无关)。谢谢Patrick!我会的。