【问题标题】:How to create an anchor and redirect to this specific anchor in Ruby on Rails如何在 Ruby on Rails 中创建一个锚点并重定向到这个特定的锚点
【发布时间】:2010-10-19 23:07:32
【问题描述】:

我正在尝试为我博客上的每条评论创建唯一的锚点,以便人们可以获取锚点的 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

【问题讨论】:

  • 为了进行屏幕滚动,url 必须指定您希望它滚动到的位置。为此,您必须在您的网址末尾添加一个#comment_123。 '#' 之后的文本需要与锚标记中的 'name' 属性的值匹配。由于缺少#,更新中的 url 不会滚动。
  • 是的,我试过了——没用!原来 :anchor 创建了这个 url # 但是使用 :name 把它改成这个,正如你所说的,这就是我所追求的.知道为什么会这样吗? #
  • 哦,好的,我明白了。对困惑感到抱歉。我更新了我的答案,但看起来您必须手动将锚点连接到 url 的末尾。否则 link_to 标签认为 :anchor 是一个 html 属性。希望这有效:)
  • 是的,这就是我最终所做的。感谢您帮助我到达那里:)
  • 您可以像这样添加锚点:post_path(@post, :anchor => "some_text")。只需将锚点作为参数传递给 post_path,而不是 link_to。

标签: ruby-on-rails ruby hyperlink anchor page-jump


【解决方案1】:

实际上,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>

【讨论】:

    【解决方案2】:

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

    所以这个:

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

    【讨论】:

    • 您应该使用 XGamerX 的答案。这可行,但不是很优雅。
    【解决方案3】:

    这是对@XGamerX 答案的改进。

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

    或者

    <%= link_to '#', post_path(comment.post, anchor: dom_id(comment)) %>
    

    【讨论】:

      【解决方案4】:

      试试这个:

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

      【讨论】:

      【解决方案5】:

      这是最好的方法:

      <%= link_to '#', post_path(comment.post, anchor: dom_id(comment.id)) %>
      

      【讨论】:

        【解决方案6】:

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

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-02-11
          • 1970-01-01
          • 1970-01-01
          • 2010-10-07
          • 1970-01-01
          • 2010-09-28
          相关资源
          最近更新 更多