Rails检查部分在ajax调用之后被完全加载

Rails check partial is fully loaded following ajax call

本文关键字:加载 之后 调用 检查部 ajax Rails      更新时间:2023-09-26

我在ajax调用后呈现一个分部:

show.js.erb

$("#notice_feed").html("<%=j render 'shared/notice_feed' %>")

_notice_feed.html.erb

<ol class="notices" id="notice_list">
  <%= render @notices %>
</ol>

这最终会呈现一个@notices的列表。每个通知的名称都列在右边,当你点击名称时,我有一些jquery可以向下滚动到相关的渲染@notice

name.on('click', function() {
  $("#absolute-div").animate({scrollTop: $('#notice_' + this.className).offset().top -200 }, 500); 
});

当你点击名称时,它会正确地向下滚动,但有时会在正确的@notice上停止滚动,而在其他@notices上则不会滚动。我怀疑问题是在整个部分列表完成渲染之前调用了jquery。我试过用包围javascript

$(window).on("load", function() {
  ...
};

但它没有启动,可能是因为它在加载原始页面时已经启动了。

如何使用jquery检查ajax调用后的部分是否已完全加载?

或者有更好的方法来识别div并准确滚动到它吗?

您可以通过以下两种方式实现:

轨道方式:

在js上制作一个方法来调用动画滚动,比如:

name.on('click', function() {
  scrolling_to(this.className);
});
function scrollin_to(name){
  $("#absolute-div").animate({scrollTop: $('#notice_' + name).offset().top -200 }, 500); 
}

然后,在show.js.erb中执行以下操作:

 scrolling_to(@notice_show.name);

Js方式:

使用ajax调用rails路由:

jQuery.ajax({
          type: 'get',    
          url: 'your url here',
          dataType: 'json',
          cache: false,
          success: function(data, textStatus){
            $("#notice_feed").html(data.msg);
            $("#absolute-div").animate({scrollTop: $('#notice_' + data.name).offset().top -200 }, 500);
          }
        });

轨道展示方式:

def show
  data ={
   msg: @notice_feed
   name: @notice_feed.name
  }
render json: data;
end

解决了它。我将.offset()更改为.position()。现在它工作得很好。

name.on('click', function() {
  $("#absolute-div").animate({scrollTop: $('#notice_' + this.className).position().top -200 }, 500); 
});

我需要@notices相对于父级的位置,而不是文档(此处为jQuery)。