2016-07-25 27 views
5

ben sadece bu kod ile değiştirme düğmesi işlevi jQuery

$('#followUser').click(function() { 
    var userId  = $(this).attr('data-userId'), 
     action  = $(this).attr('data-action'), 
     currentUser = $(this).attr('data-currentUserId'); 

    $.ajax({ 
     method: 'POST', 
     url: "/sci-profile/profile/follow", 
     data: { 
      userId: currentUser, 
      profileUserId: userId, 
      action: action 
     }, 
     success: function(response) 
     { 
      $('#followUser').attr('id', 'unFollowUser') 
          .text('Unfollow') 
          .fadeOut(50) 
          .delay(50) 
          .fadeIn(50); 
     } 
    }); 
}); 

tıklamada düğmeye içeriğini ve işlevselliğini değiştirmek istedim ve jQuery

ile bu kodu çalıştı

{% if followsId == null %} 
      <div id="followUser" class="follow" data-userId="{{ profileUserData.id }}" data-currentUserId="{{ loggedUserData.id }}" data-action="follow"> 
       Follow 
      </div> 
{% else %} 
      <div id="unFollowUser" class="follow" data-followsId="{{ followsId }}"> 
       Unfollow 
      </div> 
{% endif %} 

dal Bu kodu var sayfadaki kaynakta farklı ID ve farklı metinler görüyorum ama ikinci kez tıklattığımda ilk düğmeyi çağırdığımda hiç değişmemişti. Bu eleman için hafızayı yenilemenin bir yolu var mı yoksa başlangıçtan yanlış bir şey mi yapıyorum?

+0

ben ha doğru olup olmadığını, bunu oy olarak doğru işaretlemek yukarı benim cevabını ve Umut d bu soru ile çözüm buldu: ** http: //stackoverflow.com/questions/38686742/reload-js-function-when-load-element-with-ajax** –

cevap

4

Ben kodunuzu bu

{% if followsId == null %} 
      <div data-action="follow" class="follow" data-user-id="{{ profileUserData.id }}"> 
       Follow 
      </div> 
{% else %} 
      <div data-action="unfollow" class="follow" data-user-id="{{ followsId }}"> 
       Unfollow 
      </div> 
{% endif %} 

oturumun :) onu kapmak çünkü, geçerli kullanıcı kimliği oturum saklamak gerek yok gibi gerektiğini düşünüyorum

Kişisel Ajax Kod bu

gibi olmalıdır
$('.follow').click(function() { 
    var _this= $(this); 
    var userId = $(this).data('user-id'); 
    var action =$(this).data('action'); 

    $.ajax({ 
     method: 'POST', 
     url: "/sci-profile/profile/follow", 
     data: { 
      profileUserId: userId, 
      action: action 
     }, 
     success: function(response) 
     { 
      if(action=="follow") 
      { 
       _this.attr('data-action', 'unfollow').text('Unfollow'); 
      } 
      else 
      { 
       _this.attr('data-action', 'follow').text('Follow'); 
      } 
     } 
    }); 
}); 

o :)

+2

+1 ve '$ kullanmak isteyebilirsiniz (document) .on ("click", ". follow", işlev (event) {var $ this = event.target; .. 'dinamik olarak eklenen (ajax belki) düğmeler için. –

+0

ohk teşekkürler .... HTML içeriğinizin AJAX'tan yüklenmediğini varsaydım. –

+0

Bu benim sorum değil :) Ben sadece soranın bir sonraki sorusu olurdu sanki ileri düşünüyorum :) –