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

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

问题描述

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

评论视图 - 失败 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 - 在浏览器中正确的 url 但没有滚动发生它只是停留在页面的顶部

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,如果我点击它,它不会被滚动到.

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/posts/please-work

推荐答案

您似乎想使用问题中的 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天全站免登陆