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

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

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


当前回答

如果这对任何人来说都很重要,下面的代码很小,工作完美无缺,从URL中获得一个哈希值并显示:

<script>
    window.onload = function () {
        let url = document.location.toString();
        let splitHash = url.split("#");
        if (splitHash[1]) {document.getElementById(splitHash[1]).click();}
    };
</script>

它所做的是检索id并触发单击事件。简单。

其他回答

这是dubbe解决方案的一个改进实现,防止滚动。

// Javascript to enable link to tab
var url = document.location.toString();
if (url.match('#')) {
    $('.nav-tabs a[href="#'+url.split('#')[1]+'"]').tab('show') ;
} 

// With HTML5 history API, we can easily prevent scrolling!
$('.nav-tabs a').on('shown.bs.tab', function (e) {
    if(history.pushState) {
        history.pushState(null, null, e.target.hash); 
    } else {
        window.location.hash = e.target.hash; //Polyfill for old browsers
    }
})

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

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

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

只需在页面上插入以下代码:

$(function(){ var hash = window.location.hash; hash && $('ul.nav a[href=“' + hash + '”]').tab('show'); $('.nav-tabs a').click(function (e) { $(this).tab('show'); var scrollm = $('body').scrollTop(); window.location.hash = this.hash; $('html,body').scrollTop(scrollm); }); });

结合其他答案,这里有一个解决方案,可以打开许多级别的嵌套选项卡:

// opens all tabs down to the specified tab
var hash = location.hash.split('?')[0];
if(hash) {
  var $link = $('[href=' + hash + ']');
  var parents = $link.parents('.tab-pane').get();
  $(parents.reverse()).each(function() {
    $('[href=#' + this.id + ']').tab('show') ;
  });
  $link.tab('show');
}

你可以在相应的TAB链接上触发一个点击事件:

$(document).ready(function(){

  if(window.location.hash != "") {
      $('a[href="' + window.location.hash + '"]').click()
  }

});