37

我正在尝试为我博客上的每条评论创建唯一的锚点,以便人们可以获取锚点的 url 并将其粘贴到他们的浏览器中,这将自动加载页面并向下滚动到页面中他们评论开始的位置.

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

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

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

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

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

如果有人可以提供帮助,我将不胜感激:)

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

# 即http://localhost:3000/posts/please-work

4

6 回答 6

81

实际上,anchor 是路径的一个选项,而不是 link_to

<%= link_to '#', post_path(comment.post, :anchor => "comment_#{comment.id}") %>

http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#M001565

link_to "Comment wall", profile_path(@profile, :anchor => "wall")
       # => <a href="/profiles/1#wall">Comment wall</a>
于 2009-04-17T11:08:30.963 回答
5

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

所以这:

 <%= 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 属性是针对该标签的。

于 2009-04-16T20:35:15.210 回答
1

这是对@XGamerX 答案的改进。

<%= link_to '#', [comment.post, { anchor: dom_id(comment) }] %>

或者

<%= link_to '#', post_path(comment.post, anchor: dom_id(comment)) %>
于 2014-06-05T17:17:29.507 回答
0

试试这个:

<%= link_to '#', post_path(comment.post), :anchor => "comment_#{comment.id}" %>
于 2009-04-16T20:34:28.940 回答
0

这是最好的方法:

<%= link_to '#', post_path(comment.post, anchor: dom_id(comment.id)) %>
于 2017-02-20T21:15:02.613 回答
-1

这些链接将向下滚动到您有如下代码的位置:

<a name="comment_1"></a>

不知道有没有帮手会帮你做,但是很简单,你可以自己写。

于 2009-04-16T20:41:17.507 回答