简体   繁体   English

单个JavaScript用于Rails中的多个记录

[英]Individual JavaScript for multiple records in Rails

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. 基本上我想做的是类似于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. 现在,我无法使用的是每个帖子的AJAX“加载更多”按钮。 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: 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. 我真的不明白JS如何在一页上处理多个记录。

I suppose this could help: https://jsfiddle.net/se708oou/2/ 我想这可能会有所帮助: https : //jsfiddle.net/se708oou/2/

Main points of difference: 主要区别点:

You should loop through all of the .load-more elements 您应该遍历所有.load-more元素

$('.load-more').each(function() {

Change reference to use this 更改参考以使用this

$(this).on('click', function() {

(Miscellaneous) This is how you take data-* in jQuery: (其他)这是您在jQuery中获取data-*的方式:

postId = $(this).data('id');

Cheers! 干杯! :) :)

Your posts div 您的帖子div

<div class="post" data-id="<%= post.id %>">
    ...
</div>

Has a class of post and a data attribute id, but in index.js.erb you are trying to select #post-<%= post.id %> 具有一类post和一个数据属性id,但是在index.js.erb中,您尝试选择#post-<%= post.id %>

That selector isn't in the dom, You need to change your selector to 该选择器不在dom中,您需要将选择器更改为

$('.post[data-id=<%= post.id %>').append('<%= j render post.replies %>');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM