2016-07-25 5 views
5

私はクリックするだけでボタンにコンテンツと機能を変更したいと、このコードではjQuery変更]ボタンの機能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); 
     } 
    }); 
}); 

でこのコードを試してみました小枝

{% 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 %} 

にこのコードを持っていますon page source私は異なるIDと異なるテキストをボタンに表示しますが、二度目にクリックすると、一度も変更していないような最初のボタンを呼び出します。その要素のメモリをリフレッシュする方法はありますか?最初から間違ったことをしていますか?

+0

Iヘクタールdはこの質問で解決策を見つけました:http://stackoverflow.com/questions/38686742/reload-js-function-when-load-element-with-ajax** –

答えて

4

は、私はあなたのコードは、この

{% 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 %} 

セッション:)からそれをつかむことができるので、現在のユーザIDでログインして保存する必要はありませんが好きだと思います

あなたのAjaxのコードは、この

ようにする必要がありますそれが正しいかどう
$('.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'); 
      } 
     } 
    }); 
}); 

は、あなたが私の答えを好きとまでそれを投票正しいとしてマークを願っています:)

+2

+1、あなたは '$ (ドキュメント).on(「クリック」、「フォロー」、function(イベント){var $ this = event.target; .. ..動的に追加された(ajax多分)ボタン。 –

+0

ohkありがとう....私はあなたのHTMLコンテンツをAJAXから読み込まないと仮定しました。 –

+0

それは私の質問ではない:)私はちょうどそれが質問者の次の問題であるかのように前方に考えています:) –

関連する問題