views:

2098

answers:

3

I'm trying to modify the class of an element if an ajax call based on that element is successful

<script type='text/javascript'>
$("#a.toggle").click(function(e){
 $.ajax({
  url: '/changeItem.php',
  dataType: 'json',
  type: 'POST',
  success: function(data,text){
   if(data.error=='')
   {
    if($(this).hasClass('class1'))
    {
     $(this).removeClass('class1');
     $(this).addClass('class2');
    }
    else if($(this).hasClass('class2'))
    {
     $(this).removeClass('class2');
     $(this).addClass('class1');
    }
   }
   else(alert(data.error));
  } 
 });
 return false;
});
</script>
<a class="toggle class1" title='toggle-this'>Item</a>

My understanding of the problem is that in the success function this references the ajax object parameters, NOT the calling dom element like it does within other places of the click function. So, how do I reference the calling dom element and check / add / remove classes?

+6  A: 

You can just store it in a variable. Example:

$("#a.toggle").click(function(e)
{
   var target = $(this);
   $.ajax({
      url: '/changeItem.php',
      dataType: 'json',
      type: 'POST',
      success: function(data,text)
      {
         if(data.error=='')
         {
            if(target.hasClass('class1'))
            {
               target
                  .removeClass('class1')
                  .addClass('class2');
            }
            else if(target.hasClass('class2'))
            {
               target
                  .removeClass('class2')
                  .addClass('class1');
            }
         }
         else(alert(data.error));
      }       
   });
   return false;
});
Dan Goldstein
+5  A: 

jQuery passes the target of the event, along with some other information about it, to your handler function. See http://docs.jquery.com/Events_%28Guide%29 for more info about this.

In your code, it'd be referenced like $(e.target).

Bill Williams
A: 

I know it's old but you can use the 'e' parameter from the click function.

Jesse