2013-05-27 62 views
1

我有兩個jQuery函數,一個用於跟蹤,另一個用於取消跟蹤,當您單擊其中任何一個時,它們都會更改爲相反的單詞。事情是,如果你點擊「關注」,它就會變成「取消關注」,但是除非你刷新,否則你不能再次點擊鏈接。這裏是我的功能:jQuery函數在另一個函數運行後不工作

$(function(){ 
    $('#follow').on('click',function(){ 
     $.ajax({ 
      type: 'POST', 
      url : 'functions/follow.php', 
      data: {follower : $.upnamespace.session_id, 
        user : $.upnamespace.p_id}, 
      success: function(result) { 
       if(result == 'followed'){ 
        $('#follow').attr('id','unfollow').text('-Unfollow'); 
       } 
      } 
     }); 
    }); 
}); 
$(function(){ 
    $('#unfollow').on('click',function(){ 
     $.ajax({ 
      type: 'POST', 
      url : 'functions/unfollow.php', 
      data: {follower : $.upnamespace.session_id, 
        user : $.upnamespace.p_id}, 
      success: function(result) { 
       if(result == 'unfollowed'){ 
        $('#unfollow').attr('id','follow').text('+Follow'); 
       } 
      } 
     }); 
    }); 
}); 

這裏是一個鏈接,另一種是除了ID爲「取消關注」相同,該文本是「-Unfollow」

<a id="follow" class="small button blue" style="color:#fff">+Follow</a> 
+0

應在特定元素從未modificate屬性ID。這只是要求解決問題。 –

回答

3

由於沒有按取消關注「T最初存在的,你需要使用事件代表團

$(document).on('click','#unfollow',function(){ 
+0

我不知道,謝謝:D – TheNytangel

+1

但是,然後點擊#follow會觸發點擊委派#unfollow太http://jsfiddle.net/W5cvK/ –

+0

_「你需要」_ - 嗯,不,你不需要,但只要你對其他點擊處理程序應用相同的更改,這也是一種解決方法。 – nnnnnn

2

您可以縮短代碼,這樣你就不會需要更改ID

$(function(){ 
    $('#follow').on('click',function(){ 
     var url = $(this).text() == '+Follow' ? 'functions/follow.php' : 'functions/unfollow.php'; 
     $.ajax({ 
      type: 'POST', 
      url : url, 
      data: {follower : $.upnamespace.session_id, user : $.upnamespace.p_id}, 
      success: function(result) { 
       if(result == 'unfollowed'){ 
        $('#follow').text('+Follow'); 
       } else if(result == 'followed') { 
        $('#follow').text('-Unfollow'); 
       } 
      } 
     }); 
    }); 
}); 
2

我不認爲改變id屬性是最好的解決方案。

嘗試像

$(function(){ 
    $('#follow').on('click',function(){ 
     var $this = $(this), type = $this.data('followType') || 'follow', follow = type == 'follow'; 
     $.ajax({ 
      type: 'POST', 
      url : 'functions/' + follow + '.php', 
      data: {follower : $.upnamespace.session_id, 
        user : $.upnamespace.p_id}, 
      success: function(result) { 
       if(result == 'followed'){ 
        $this.text('-Unfollow').data('followType', 'unfollow'); 
       } else if(result == 'unfollowed'){ 
        $this.text('+Follow').data('followType', 'follow');; 
       } 
      } 
     }); 
    }); 
}); 
相關問題