如何在 Ruby on Rails 中创建锚点并重定向到该特定锚点
我正在尝试为博客上的每条评论创建独特的锚点,以便人们可以获取锚点的网址并将其粘贴到浏览器中,浏览器将自动加载页面并向下滚动到页面中评论开始的位置。
也许我的方法是错误的,但我已经尝试过了,但没有成功。
评论视图 - 失败 1 - 当粘贴到浏览器中时,此链接不会向下滚动到所需位置
<%= link_to '#', :controller => 'posts', :action => 'show', :id => comment.post, :anchor => 'comment_' << comment.id.to_s %>
评论控制器 - 失败 2 - 浏览器中的网址正确,但没有滚动发生,它只是停留在页面顶部
redirect_to :controller => 'posts', :action => 'show', :id => @post, :anchor => 'comment_' + @comment.id.to_s
如果有人可以帮助我'我将非常感激:)
更新:下面的解决方案几乎可以工作,但是我得到了以下 URL,如果我单击它,则不会滚动到该 URL。
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.
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 %>
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 :)
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
尝试这个:
Try this:
这是最好的方法:
this is best way:
这些链接将向下滚动到您有如下代码的位置:
我不知道是否有帮助程序可以为您完成此操作,但它非常简单,您可以编写自己的代码。
These links will scroll down to position where you have code like:
I don't know if there are helpers that will do it for you, but it is very simple and you can write your own.
实际上,锚点是路径的一个选项,而不是 link_to
http:// /api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#M001565
Actually, anchor is an option for the path, not for the link_to
http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#M001565
您似乎想使用问题中的
link_to
代码。 然后,在您的评论列表中,您必须确保链接中有一个名为相同内容的锚标记。因此:
将生成类似这样的内容
您必须手动附加
#comment_
否则 link_to 方法认为您传递的 :anchor 属性是针对该标记的。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.So this:
will generate something like this
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.这是对 @XGamerX 答案的改进。
或者
Here's an improvement on @XGamerX's answer.
Or