【问题标题】:Bootstrap 3: how to link directly to a tab from another page in Rails 4Bootstrap 3:如何直接链接到 Rails 4 中另一个页面的选项卡
【发布时间】:2016-01-23 11:41:39
【问题描述】:

我正在使用 Rails 4 和 Bootstrap 3 构建一个 Web 应用程序。

在其中一个页面中,我有以下Bootstrap tabs

<ul class="nav nav-tabs" role="tablist">
    <li role="presentation" class="active"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab"><span class="glyphicon glyphicon-user" aria-hidden="true"></span> Profile</a></li>
    <li role="presentation"><a href="#billing" aria-controls="billing" role="tab" data-toggle="tab"><span class="glyphicon glyphicon-credit-card" aria-hidden="true"></span> Billing</a></li>
    <li role="presentation"><a href="#expert" aria-controls="expert" role="tab" data-toggle="tab"><span class="glyphicon glyphicon-briefcase" aria-hidden="true"></span> Expert</a></li>
  </ul>

然后,这些选项卡中的以下内容:

<div class="tab-content">
    <div role="tabpanel" class="tab-pane active" id="profile">
    </div>
    <div role="tabpanel" class="tab-pane" id="billing">
    </div>
    <div role="tabpanel" class="tab-pane" id="expert">
    </div>
</div>

当我将鼠标悬停在这些选项卡中时,我看到直接 URL 是,即:http://localhost:3000/account/edit#profilehttp://localhost:3000/account/edit#billinghttp://localhost:3000/account/edit#expert

但是,当我尝试从另一个页面直接链接到选项卡时,活动选项卡仍然是第一个(不是我链接到的)。

两个音符:

  1. 正如in the markdown section in the documentation 解释的那样,我正在使用“没有任何 JavaScript”的引导选项卡。

  2. 我想使用 Rails link_to helper 链接到这些选项卡。

知道为什么这不起作用吗?

【问题讨论】:

  • 您希望 link_to 助手仅链接到其中一个选项卡,对吗?
  • 是的,这正是我想要的。此链接更具体:http://localhost:3000/account/edit#expert

标签: ruby-on-rails twitter-bootstrap ruby-on-rails-4 hyperlink tabs


【解决方案1】:

您正在视图中设置活动选项卡

<li role="presentation" class="active"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab"><span class="glyphicon glyphicon-user" aria-hidden="true"></span> Profile</a></li>

哪个优先。

如果你想让它工作,你需要将活动类添加到 url 锚中引用的任何选项卡(#expert,在你的情况下)

this post if you need code reference.

***编辑: 由于您没有使用js,因此请使用底部的答案,通过解析请求动态确定活动选项卡

【讨论】:

    【解决方案2】:

    我认为如果不添加一些 javascript,您将无法完成您所追求的目标,因为选项卡用于页面内导航,而不是页面间导航。此外,这些选项卡上甚至不需要 href 标记,因为它是 data-toggle 属性控制要显示的选项卡窗格。

    如果添加一个小的 javascript sn-p 是一个可行的选项,当页面被导航到时,这将切换到相应的选项卡。

    hash = window.location.hash
    $("a[href=#{hash}]").click()
    

    https://jsfiddle.net/tL7sutnt/

    【讨论】:

    • 感谢您的回答。我绝对可以使用一些 JS,我只是在我的问题中指定我不是因为我自己找到的大多数其他答案都是在使用 JS 实现选项卡的情况下。如果我想采用您的解决方案,您建议在哪里包含此 JS 代码:在带有 标签的视图中、在专用的 .coffee 文件中或其他地方?
    • 在可能的情况下,最好将javascript(或者在这种情况下,coffeescript)放在名称与控制器名称匹配的专用文件中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 2013-02-15
    • 1970-01-01
    • 2016-06-22
    • 2017-08-21
    • 1970-01-01
    • 2013-04-08
    相关资源
    最近更新 更多