简体   繁体   English

Rails在重新加载时触发js动作

[英]rails triggering js action on reload

I have a rails4 app. 我有一个rails4应用程序。 I'd like to trigger some js events on page load, but only if user comes from a given page. 我想在页面加载时触发一些js事件,但前提是用户来自给定页面。

By default all the comment replies are hidden on the post#index page. 默认情况下,所有评论回复都隐藏在post#index页面上。 If user clicks on a div then the corresponding replies become visible. 如果用户单击div,则相应的答复将变为可见。

Now I want to have a given post_comment_reply div visible by default on page load, if a user comes to the page via clicking on the notification belonging to the post_comment_reply . 现在,如果用户通过单击属于post_comment_reply的通知进入该页面,则我希望在页面加载时默认情况下具有给定的post_comment_reply div。

What is the preferred way in rails to do that? 在rails中这样做的首选方式是什么?

js js

$(document).on('click', '.open-post-comment-reply', function (event) {
  var post_comment_id = $(this).data('pcid');
  $('#post-comment-replies-' + post_comment_id).toggle();
});

您可以将cookie附加在给定页面上的onclick事件链接中,然后在显示注释框后将其删除。

Setting a cookie would work, as suggested by another user. 如另一个用户所建议的那样,设置cookie将起作用。 You could also check the request.referrer in rails to see where they came from. 您也可以在rails中检查request.referrer以查看它们的来源。

Couple of ways to handle triggering the js from there. 从那里处理触发js的几种方法。 You could pass the referrer value to the js with something like: 您可以使用以下方式将引荐来源网址值传递给js:

<div class="some-class" data-referrer="<%= request.referrer %>">

Then in your js, if you're using jQuery: 然后在您的js中,如果您使用的是jQuery:

if ($('.some-class').data('referrer') == 'whatever_url'){
  // run your code
}

You could also put a conditional directly in the view. 您也可以直接在视图中添加条件。 Probably not as clean but something like: 可能不那么干净,但类似:

<% if request.referrer == 'whatever_url' %>
  <script>
    // code to run
  </script>
<% end %>

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

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