2013-08-31 38 views
0

我正在使用「infinite scroll plugin」來添加內容。 在每一個崗位我有一個Like按鈕,但它並不適用於通過 「無限滾動」未來添加內容的Jquery.on

enter image description here

HTML(ERB)

<% current_user.likes?(post) ? like_icon_name = "icon-thumbs-up" : like_icon_name = "icon-thumbs-up-alt" %> 

<%=link_to "", url_for(controller: "like", action:"toggle", resource_name: post.class.to_s, resource_id: post.id), class:"like #{like_icon_name}", remote: true%> 

HTML(生成)

添加的內容合作
<a class="like icon-thumbs-up-alt" data-remote="true" href="/it/like/toggle?resource_id=1&amp;resource_name=Photo"></a> 

like.js

$(document).on("ready page:load", function() { 
     $("a[data-remote].like").on("ajax:success", function(e, data, status, xhr){ 
     if(xhr.responseText){ 
      $(e.target).toggleClass("icon-thumbs-up-alt icon-thumbs-up"); 
     }else{ 
      console.log(xhr); 
     } 

    }); 
}); 

Scrolling.js

// usage: 
// $(elem).infinitescroll(options,[callback]); 

// infinitescroll() is called on the element that surrounds 
// the items you will be loading more of 

$(document).on('ready page:load', function() { 

    $('#posts').infinitescroll({ 

     navSelector : "nav.pagination",    
        // selector for the paged navigation (it will be hidden) 

     nextSelector : "nav.pagination .next a:first",  
        // selector for the NEXT link (to page 2) 

     itemSelector : "#posts div.post",   
        // selector for all items you'll retrieve 

     debug  : false,      
        // enable debug messaging (to console.log) 

    }, function(arrayOfNewElems){ 

      $(document).trigger('scrolled'); 

      // optional callback when new content is successfully loaded in. 

      // keyword `this` will refer to the new DOM content that was just added. 
      // as of 1.5, `this` matches the element you called the plugin on (e.g. #content) 
      //     all the new elements that were found are passed in as an array 

     }); 


}); 

頁:負載爲 「turbolinks

+0

您可以加入有關的,像布頓的單擊事件的代碼? – CronosS

+0

完成。問題更新 – sparkle

+1

Thx,嘗試編輯like.js:'$(document).on(「ajax:success」,「a [data-remote] .like」,function(....' – CronosS

回答

1

的問題是,你的事件處理常式是綁定到一個元素兩個直)注入進入頁面。

事件處理程序只綁定到當前選定的元素;在代碼調用.on()時,頁面上必須存在 。 [來源:jquery doc]

你必須使用委託的事件附加事件處理程序。在這裏完成由調用上提供一個選擇(),綁定到一個元素that is guaranteed to be present at the time the delegated event handler is attached (e.g. the document element)

$(document).on("ajax:success", "a[data-remote].like", function(...){ 
    ... 
}); 
+0

我得到了我的事件兩次,你知道如何防止這個? – sparkle