Jquery .on用于未来添加的内容

时间:2013-08-31 16:54:02

标签: javascript jquery data-binding

我正在使用“infinite scroll plugin”来添加内容。 在每个帖子中我都有一个Like按钮,但它不适用于通过“无限滚动”添加的内容

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

1 个答案:

答案 0 :(得分:1)

问题在于你的evant处理程序(直接 - )绑定到注入元素到页面中。

  

事件处理程序仅绑定到当前选定的元素;他们   在您的代码调用.on()时页面上必须存在。 [来源:jquery doc]

您必须使用委派事件来附加事件处理程序。通过在对on()的调用中提供一个选择器来完成此处,绑定到元素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(...){
    ...
});