Adding a class to a button in jquery
I am trying to add a css class to my button a开发者_JAVA技巧fter some ajax:
$('a.vote-up-0').click(function() {
var id = $(this).siblings('.reply-id').val();
var ajax_auth_token = $('#auth_token').val();
$.post('user/?action=ajax', {
vote_type: 'up',
reply_id: id,
auth_token: ajax_auth_token
}, function(data, return_status) {
var json_data = jQuery.parseJSON(data);
switch(json_data.r_message)
{
case "success":
output = "Yay it works!"; // change
alert(output);
$(this).addClass('vote-up-1'); // ** the culprit **
break;
The alert works, however it does not add the class vote-up-1 to it. There are several instances of the same class (i.e. vote-up-0) on the page, so If I change (this) to 'vote-up-0', it changes all of them. Anyone have any ideas?
Up at the top of your "click" handler, stash the this
value:
var theButton = this;
Then, in your ".post()" handler:
$(theButton).addClass('vote-up-1');
The problem is that this
will not refer to the button when jQuery calls your ".post()" handler. Thus, you save a copy into a local variable, and it'll be there waiting for the handler when the time comes.
Brother: $(this).addClass('vote-up-1'); // ** the culprit **
is truly the culprit. $(this)
is not available in this scope so it's better that you get the handle of the button before doing any ajax. such as:
var btnHnd = $(this);
Now you can do the post stuff: $.post('user/?action=ajax', { ...
change this
$(putyourbuttonidhere).addClass('vote-up-1');
精彩评论