I've been trying to wrap my head around this for days now, but I can't seem to find a solution for this problem.
Basically what I want to do is a feed similar to Facebook. A feed with multiple posts, of which each has comments/replies.
Now what I can't get to work is an AJAX "Load more" button for each post. I've only got it working for all posts at once, but not for individual ones.
What I have so far:
The feed:
<% @posts.each do |post| %>
<%= render "posts/thread", post: post %>
<% end %>
The threads:
<%= render post %>
<% replies = post.replies.paginate(:page => params["replies#{post.id.to_s}"], :per_page => 2) %>
<%= render replies %>
<%= will_paginate replies, :param_name => 'replies'+post.id.to_s %>
<%= link_to "Load More", "#", class: "load-more", id: post.id, :remote => true %>
The posts:
<div class="post" data-id="<%= post.id %>">
## content ##
</div>
pagination.coffee:
jQuery ->
$('.load-more').on 'click', ->
postId = $(this).attr('id')
more_posts_url = $('#post-'+postId+' .pagination .next_page').attr('href')
if more_posts_url
$('.load-more').html('<img src="/assets/ajax-loader.gif" alt="Loading..." title="Loading..." />')
$.getScript more_posts_url
return
return
index.js.erb:
<%= @posts.each do |post| %>
$('#post-<%= post.id %>').append('<%= j render post.replies %>');
<% end %>
But this does nothing.
I really don't understand how JS works for multiple records on one page.
答案 0 :(得分:0)
我想这可能会有所帮助:https://jsfiddle.net/se708oou/2/
主要的不同点:
您应该遍历所有.load-more
元素
$('.load-more').each(function() {
更改使用this
$(this).on('click', function() {
(杂项)这是你在jQuery中使用data-*
的方法:
postId = $(this).data('id');
干杯! :)
答案 1 :(得分:0)
你的帖子div
<div class="post" data-id="<%= post.id %>">
...
</div>
有一类帖子和数据属性ID,但在index.js.erb中你试图选择#post-<%= post.id %>
该选择器不在dom中,您需要将选择器更改为
$('.post[data-id=<%= post.id %>').append('<%= j render post.replies %>');