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

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

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


当前回答

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

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

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

其他回答

我知道这个线程非常旧,但我将在这里留下我自己的实现:

$(function () {
  // some initialization code

  addTabBehavior()
})

// Initialize events and change tab on first page load.
function addTabBehavior() {
  $('.nav-tabs a').on('show.bs.tab', e => {
    window.location.hash = e.target.hash.replace('nav-', '')
  })

  $(window).on('popstate', e => {
    changeTab()
  })

  changeTab()
}

// Change the current tab and URL hash; if don't have any hash
// in URL, so activate the first tab and update the URL hash.
function changeTab() {
  const hash = getUrlHash()

  if (hash) {
    $(`.nav-tabs a[href="#nav-${hash}"]`).tab('show')
  } else {
    $('.nav-tabs a').first().tab('show')
  }
}

// Get the hash from URL. Ex: www.example.com/#tab1
function getUrlHash() {
  return window.location.hash.slice(1)
}

注意,我使用了一个导航类前缀来导航链接。

用于引导5.1重定向到特定的选项卡

var hash = location.hash.replace(/^#/, '');
if (hash) {
var someVarName = $('.nav-tabs a[href="#' + hash + '"]');
var tab = new bootstrap.Tab(someVarName);
tab.show();
}

更改页面重新加载的散列

$('.nav-tabs a').on('shown.bs.tab', function (e) {
  window.location.hash = e.target.hash;
  window.scrollTo(0, 0);
})

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

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

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

基于Peter的回答,并结合https://stackoverflow.com/a/901144/1604205,下面是JS中的代码:

<script>
    const params = new Proxy(new URLSearchParams(window.location.search), {
        get: (searchParams, prop) => searchParams.get(prop),
    });
    $activetabhome = (params.activeTab === null || params.activeTab == 'home') ? 'class="active"' : '';
    $activetabprofile = (params.activeTab == 'profile') ? 'class="active"' : '';
</script>
<li $activetabhome><a href="#home">Home</a></li>
<li $activetabprofile><a href="#profile">Profile</a></li>

下面是我所做的,非常简单,并且提供你的标签链接有一个与它们相关的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。

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