如何在Ruby on Rails中创建锚点并重定向到此特定锚点 [英] How to create an anchor and redirect to this specific anchor in Ruby on Rails

查看:242
本文介绍了如何在Ruby on Rails中创建锚点并重定向到此特定锚点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的博客上的每条评论创建独特的锚点,这样一个人就可以获取一个锚点的网址并将其粘贴到浏览器中,这将自动加载页面并向下滚动到页面中的点他们的评论开始了

I'm trying to create unique anchors for every comment on my blog so a person can take the url of an anchor and paste it in their browser, which will automatically load the page and scroll down to the point in the page where their comment starts.

也许我会以错误的方式解决这个问题,但我已经尝试了这个但是无济于事。

Perhaps I'm going about this the wrong way but I've tried this which was to no avail.

评论视图 - 失败1 - 当粘贴在浏览器中时,此链接不会向下滚动到所需位置

Comment view - Fail 1 - when pasted in a browser this link does not scroll down to the desired position

<%= link_to '#', :controller => 'posts', :action => 'show', :id => comment.post, :anchor => 'comment_' << comment.id.to_s %>

评论控制器 - 失败2 - 在浏览器中更正网址但没有滚动发生它只是停留在顶部页面

Comments controller - Fail 2 - Correct url in browser but no scrolling happens it just stays at the top of the page

redirect_to :controller => 'posts', :action => 'show', :id => @post, :anchor => 'comment_' + @comment.id.to_s

如果有人可以提供帮助,我会非常感激: )

If someone could help I'd be very grateful :)

更新:下面的解决方案几乎可以正常工作,但是如果我点击它,我会提供以下URL,但不会滚动到该URL。

UPDATE: The solutions below almost work, however I come out with the following URL which isn't being scrolled to if I click on it.


http:// localhost:3000 /帖子/请工作

推荐答案

看起来你想要使用 link_to 您在问题中的代码。然后在您的评论列表中,您必须确保链接中有一个名为相同内容的锚标记。

It looks like you want to use the link_to code that you have in your question. Then in your list of comments you have to make sure that you have an anchor tag named the same thing in the link.

所以这个:

 <%= link_to 'Your comment', post_path(@comment.post) + "#comment_#{@comment.id.to_s}" %>

会产生类似这样的东西

 <a href="localhost:3000/posts/2#1comment_234">Your comment</a>

 /* html code */     

 <a name="comment_1234">This is a comment</a>

您必须手动处理 #comment _ 否则link_to方法认为您传递的:anchor属性是针对该标记的。

You have to manually tack on the #comment_ otherwise the link_to method thinks that the :anchor attribute that you are passing it is for that tag.

这篇关于如何在Ruby on Rails中创建锚点并重定向到此特定锚点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆