2016-07-31 62 views
0
$('#followUser').click(function() { 
     var userId  = $(this).attr('data-userId'), 
      action  = $(this).attr('data-action'), 
      currentUser = $(this).attr('data-currentUserId'), 
      elem   = $(this); 

     $.ajax({ 
      method: 'POST', 
      url: "/sci-profile/profile/follow", 
      data: { 
       userId: currentUser, 
       profileUserId: userId, 
       action: action 
      }, 
      success: function(response) 
      { 
       elem.parent().load(window.location.href + ' #unFollowUser'); 
      } 
     }); 
    }); 

負荷要素點擊按鈕,加載JS新的div其所有的內容,這是很好的,但是,當加載新的div問題此刻開始後。刷新JS功能時用AJAX

JS不認識新的ID。而當我點擊新按鈕時,什麼都不會發生,因爲當新元素不存在時JS函數已經加載。

有沒有辦法讓一些監聽器檢查新的DIV的負載,然後加載對應於該元素的JS功能ID

+1

[Event delegation](http://stackoverflow.com/questions/1687296/what-is-dom-event-delegation?answertab=votes#tab-top) – adeneo

+1

http://stackoverflow.com/questions/8594408/reload-javascript-file-after-an-ajax-request也許這個鏈接可以提供幫助。 –

+0

我花了一些時間瞭解如何使用.delegate()謝謝@Jo_bast提示。 –

回答

0

是的,我做到了。

這是HTML

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

而且有JS代碼

$('.follow').delegate('div', 'click', function(){ 
    action  = $(this).attr('data-action'); 
    elem   = $(this); 

    if (action == 'follow'){ 
     var userId  = $(this).attr('data-userId'), 
      currentUser = $(this).attr('data-currentUserId'); 

     $.ajax({ 
      method: 'POST', 
      url: "/sci-profile/profile/follow", 
      data: { 
       userId: currentUser, 
       profileUserId: userId, 
       action: action 
      }, 
      success: function(response) 
      { 
       elem.parent().load(window.location.href + ' #unFollowUser'); 
      } 
     }); 
    } 

    if (action == 'unFollow'){ 
     var followsId = $(this).attr('data-followsId'); 

     $.ajax({ 
      method: 'DELETE', 
      url: "/sci-profile/profile/unFollow", 
      data: { 
       followsId: followsId 
      }, 
      success: function(response) 
      { 
       elem.parent().load(window.location.href + ' #followUser'); 
      } 
     }); 
    } 
}); 

我希望這將幫助別人。

+0

.delegate已棄用。改用.on代替。 – ArtemSky

1

您應該使用委託

例如,你有這個標記

<div id=contentWrapper> 
    .....some content here.... 
    <button type=button id=followUser></button> 
</div> 
  • #contentWrapper - 靜態塊
  • 東西里面 - 動態內容

現在你應該像這樣綁定你的事件

$('#contentWrapper').on('click', '#followUser' 'function() { 
    ...code here... 
});