jQuery选择器$(this)没有按预期工作

Moh*_*mad 1 jquery

在提交ajax请求时,我想在发送之前切换一个类,在错误时将其切换回来,或者如果一切正常则保留它.但$(this)选择器似乎没有工作,我不知道为什么.我正在使用jQuery 1.4.3.

HTML

<a class="vote-down vote-down-112 state-3" data-postid="112" data-voteid="6">down</a>
Run Code Online (Sandbox Code Playgroud)

JS

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

Nic*_*ver 6

this默认情况下是指ajax对象本身,如果你想this成为特定的东西,可以使用该context选项来设置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;
}); 
Run Code Online (Sandbox Code Playgroud)

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

  • +1我认为`context`属性可能是那些鲜为人知的特征之一. (2认同)