开发者

jQuery selector $(this) not working as expected

开发者 https://www.devze.com 2023-01-26 23:23 出处:网络
When submitting an ajax request, I would like to toggle a class before send, toggle it back on error开发者_JAVA技巧, or keep it if everything turns out ok. But the $(this) selector does not seem to be

When submitting an ajax request, I would like to toggle a class before send, toggle it back on error开发者_JAVA技巧, or keep it if everything turns out ok. But the $(this) selector does not seem to be working and I'm not sure why. I'm using jQuery 1.4.3.

html

<a class="vote-down vote-down-112 state-3" data-postid="112" data-voteid="6">down</a>

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


this by default refers to the ajax object itself, if you want this to be something specific, use the context option to set what this is in your callbacks, like 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;
}); 

I removed the function arguments just to clean up, they're not needed if you're not using them.


Common mistake. this refers to the XHR request, not to the element:

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

That is because jQuery calls you error and beforeSend function like this: userfunction.apply( xhr[, args] );, which makes the this keyword refer to the XHR.

0

精彩评论

暂无评论...
验证码 换一张
取 消