2011-12-01 55 views
0

我是JS的新手。 .get()成功后,我试图更改按钮的背景颜色。.get()成功后更改元素样式

这里是例子:http://jsfiddle.net/csTpG/95/

这有什么错我的代码?


$('.add').click(function() { 
    var productID = $(this).attr('name'); 
    $.get('/',{item_id : productID}, function() { 
     $(this).addClass('clicked'); 
    }); 
    return false; 
}); 

<button class="add">click me</button> 

回答

2

你的按钮有没有name属性。

除此之外,引用点击的元素的$.get回调外回调使用它:

$('.add').click(function() { 
    var productID = $(this).attr('name'); 
     // keep a reference to the element in this scope 
    var self = this; 
    $.get('/',{item_id : productID}, function() { 
      // use the reference in the callback 
     $(self).addClass('clicked'); 
    }); 
    return false; 
}); 
0

里面的$.get回调,this是不是你的元素。您首先需要保存对this的引用。

$('.add').click(function() { 
    var $this = $(this), 
    productID = $this.attr('name'); 
    $.get('/',{item_id : productID}, function() { 
     $this.addClass('clicked'); 
    }); 
    return false; 
});