我正在开发一个网页,其中我使用Twitter的引导框架和他们的引导标签JS。它的工作很好,除了一些小问题,其中之一是我不知道如何直接从外部链接到一个特定的选项卡。例如:

<a href="facility.php#home">Home</a>
<a href="facility.php#notes">Notes</a>

当从外部页面点击链接时,应该分别转到Home选项卡和Notes选项卡


当前回答

对于引导3:

$('.nav-tabs a[href="#' + tabID + '"]').tab('show');

https://jsfiddle.net/DTcHh/6638/

其他回答

这是我对这个问题的解决方案,可能有点晚了。但它可能会帮助其他人:

// Javascript to enable link to tab
var hash = location.hash.replace(/^#/, '');  // ^ means starting, meaning only match the first hash
if (hash) {
    $('.nav-tabs a[href="#' + hash + '"]').tab('show');
} 

// Change hash for page-reload
$('.nav-tabs a').on('shown.bs.tab', function (e) {
    window.location.hash = e.target.hash;
})

这段代码根据#散列选择正确的选项卡,并在单击选项卡时添加正确的#散列。(使用jquery)

在Coffeescript中:

$(document).ready ->
    if location.hash != ''
        $('a[href="'+location.hash+'"]').tab('show')

    $('a[data-toggle="tab"]').on 'shown', (e) ->
        location.hash = $(e.target).attr('href').substr(1)

或在JS中:

$(document).ready(function() {
    if (location.hash !== '') $('a[href="' + location.hash + '"]').tab('show');
    return $('a[data-toggle="tab"]').on('shown', function(e) {
      return location.hash = $(e.target).attr('href').substr(1);
    });
});

下面是我所做的,非常简单,并且提供你的标签链接有一个与它们相关的ID,你可以获得href属性,并将其传递给显示标签内容的函数:

<script type="text/javascript">
        jQuery(document).ready(function() {
            var hash = document.location.hash;
            var prefix = "tab_";
            if (hash) {
                var tab = jQuery(hash.replace(prefix,"")).attr('href');
                jQuery('.nav-tabs a[href='+tab+']').tab('show');
            }
        });
        </script>

然后在你的url中,你可以像这样添加散列:#tab_tab1, 'tab_'部分从散列本身中删除,因此在nav-tabs (tabid1)中实际的标签链接的ID被放在后面,所以你的url看起来像:www.mydomain.com/index.php#tab_tabid1。

这对我来说是完美的,希望它能帮助其他人:-)

我用ajax做了这样的链接#!#(例如/test.com#!#test3),但你可以随心所欲地修改它

$(document).ready(function() {

       let hash = document.location.hash;
       let prefix = "!#";

       //change hash url on page reload
       if (hash) {
         $('.nav-tabs a[href=\"'+hash.replace(prefix,"")+'\"]').tab('show');
       } 

       // change hash url on switch tab
       $('.nav-tabs a').on('shown.bs.tab', function (e) {
          window.location.hash = e.target.hash.replace("#", "#" + prefix);
       });
 });

Github上的简单页面示例

我建议你使用Bootstrap作者在GitHub上的问题跟踪器上提供的代码:

var hash = location.hash
  , hashPieces = hash.split('?')
  , activeTab = $('[href=' + hashPieces[0] + ']');
activeTab && activeTab.tab('show');

你可以在这个问题的链接上找到更多关于他们为什么不选择支持它的信息。