Dam*_*ian 37 ruby anchor ruby-on-rails hyperlink page-jump
我正在尝试为我博客上的每条评论创建独特的锚点,这样一个人就可以获取一个锚点的网址并将其粘贴到浏览器中,这将自动加载页面并向下滚动到页面中评论开始的位置.
也许我正在以错误的方式解决这个问题,但我已经尝试过这个但是无济于事.
注释视图 - 失败1 - 当粘贴在浏览器中时,此链接不会向下滚动到所需位置
<%= link_to '#', :controller => 'posts', :action => 'show', :id => comment.post, :anchor => 'comment_' << comment.id.to_s %>
Run Code Online (Sandbox Code Playgroud)
注释控制器 - 失败2 - 在浏览器中更正URL但没有滚动发生它只是停留在页面顶部
redirect_to :controller => 'posts', :action => 'show', :id => @post, :anchor => 'comment_' + @comment.id.to_s
Run Code Online (Sandbox Code Playgroud)
如果有人可以帮助我会非常感激:)
更新:下面的解决方案几乎可以工作,但是我提出了以下URL,如果我点击它就不会滚动到它.
小智 81
实际上,锚是路径的选项,而不是link_to
<%= link_to '#', post_path(comment.post, :anchor => "comment_#{comment.id}") %>
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
您似乎想要使用问题中的link_to代码.然后在您的评论列表中,您必须确保在链接中有一个名为相同内容的锚标记.
所以这:
<%= link_to 'Your comment', post_path(@comment.post) + "#comment_#{@comment.id.to_s}" %>
Run Code Online (Sandbox Code Playgroud)
会产生这样的东西
<a href="localhost:3000/posts/2#1comment_234">Your comment</a>
/* html code */
<a name="comment_1234">This is a comment</a>
Run Code Online (Sandbox Code Playgroud)
您必须手动处理,#comment_否则link_to方法认为您传递的:anchor属性是针对该标记的.
| 归档时间: |
|
| 查看次数: |
28761 次 |
| 最近记录: |