Rails 3.1.3 使用带有 link_to 标记的锚属性从 posts/index 到 posts/show/id 不起作用

2023-12-23

我在 posts/index 视图上使用 link_to 标签,并希望使用锚点将其链接到 posts/show/id 视图,使其向下滚动到评论表单。由于某种原因,我无法让锚点工作。这是我的代码:

在帖子/索引中

<%= link_to 'Add a Comment', post, :anchor => 'comment_form' %>

这无法将 # 符号附加到链接末尾,因此它只是 localhost:3000/posts/id。 我还尝试了 link_to 的许多变体,包括:

<%= link_to 'Add a Comment', post(:anchor => 'comment_form' %>

and

<%= link_to 'Add a Comment', :controller => 'posts', :action => 'show', :id => @post, :anchor => 'comment_form' %>

但我没有运气。

这是我的帖子#show action:

  def show
    @post = Post.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @post }
    end
  end

这是我希望锚点滚动到的帖子/显示视图:

<h2><a name="comment_form" id="comment_form">Add a comment:</a></h2>

此外,如果我链接到索引页面上的某些内容,上述任何操作都有效,因为我可以看到哈希 # 已附加到输出的 url 中。由于某种原因,尝试链接到显示页面时它不起作用。有什么帮助吗?


尝试这个:

link_to('Add a comment', post_path(post, :anchor => 'comment_form'))

第二个参数link_to通常按原样传递给url_for,第三个参数用作属性哈希<a>最终生成的元素。

所以在你的第一个例子中,你传递了一个Post对象作为第二个参数,哈希作为第三个参数。只有Post将被传递给url_for。它永远不会看到包含以下内容的哈希值:anchor选项,这样您就不会在生成的 URL 末尾看到锚点。 (但是你可能会看到anchor="comment_form"生成的属性<a>元素。)

你的第二个例子在语法上是不正确的。我想这会导致错误。

你的第三个例子......应该有效。我不知道为什么没有:-)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Rails 3.1.3 使用带有 link_to 标记的锚属性从 posts/index 到 posts/show/id 不起作用 的相关文章

随机推荐