2013-02-27 60 views
4

下面是我的簡單代碼,其中想要爲Gmail樣式的代碼添加書籤。toggleClass在ajax案例中無法正常工作

$(this).toggleClass('favitedited');

以上聲明不起作用。得到ajax響應後,明星不會變成黃色的。 但如果你把上面的語句放在ajax塊之外,它就可以工作。不能理解爲什麼會發生。

<html> 
<head> 
<style> 
.star { 
    background-color: transparent; 
    background-image: url('http://www.technicalkeeda.com/img/images/star-off.png'); 
    background-repeat:no-repeat; 
    display: block; 
    height:16px; 
    width:16px; 
    float:left; 
} 

.star.favorited { 
    text-indent: -5000px; 
    background-color: transparent; 
    background-image: url('http://www.technicalkeeda.com/img/images/star-on.png'); 
    background-repeat:no-repeat; 
    height:16px; 
    width:16px; 
    float:left; 
} 

span{ 
color: #2864B4; 
} 
</style> 

<script type="text/javascript" src="http://www.technicalkeeda.com/js/javascripts/plugin/jquery.js"></script> 
<script> 
    $(document).ready(function(){ 
     $('.star').click(function() { 
       var id = $(this).parents('div').attr('id');    

       $.ajax({ 
         type: "post", 
         url: "http://www.technicalkeeda.com/demos/bookmark", 
         cache: false,    
         data:{'bookmarkId': id}, 
         success: function(response){ 
          alert('response' +response); 
          if(response=='true'){         
           $(this).toggleClass('favorited');            
          }else{ 
           alert('Sorry Unable bookmark..'); 
          } 

         }, 
         error: function(){      
          alert('Error while request..'); 
         } 
        }); 
      }); 
    }); 
</script> 
</head> 
<body> 
<div id="1000"><a href="javascript:void(0);" class="star" ></a><span>Php CodeIgniter Server Side Form Validation Example</span></div> 
<div id="2000"><a href="javascript:void(0);" class="star"></a><span>Live Search Using Jquery Ajax, Php Codeigniter and Mysql</span></div> 
<div id="3000"><a href="javascript:void(0);" class="star"></a><span>Voting system Using jQuery Ajax and Php Codeigniter Framework</span></div> 
</body> 
</html> 
+0

是的,如果你硬編碼響應爲真,仍然不能正常工作 – Vicky 2013-02-27 02:19:56

回答

5

在Ajax回調this不是.star元件,它是一個對象jqXHR。這樣做:

$(".star").click(function() { 
    var $this = $(this); 
    /* snip */ 
    if (response == 'true') { 
     $this.toggleClass('favorited'); 
    /* snip */ 
+0

謝謝@爆炸藥丸 – Vicky 2013-02-27 02:22:32

+0

right-o!出於好奇,在這些情況下,我看到很多$ this的賦值。這個命名約定是否對像elem這樣的基本字符串有什麼實際好處? – 2013-02-27 02:22:43

+1

@KaiQing我傾向於命名包含以'$'開頭的jQuery集合的變量,不管它們是什麼,所以'$ this'只是自動產生的。除了清晰度之外,沒有任何好處;如果您對您/您的開發團隊不清楚,請隨時使用 – 2013-02-27 02:23:41

2

$(this)已不在您的回覆範圍內。你可以在你的迴應打過去了引用它是這樣的...

$('.star').click(function() { 
    var elem = $(this); 

然後

elem.toggleClass('favorited'); 
0

要保持(幾乎所有)相同,設置AJAX調用的上下文:

$ .ajax({上下文:this, success:function(){...} });

在另一方面,我剛剛做了類似的推薦給其他人關於如何設置點擊事件東西...

$('document.body').on('click', '.star', function() {....}); 

會給你相同的功能,提高性能,並自動適應任何項目添加或刪除與星級的文件。