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

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

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


当前回答

这是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
    }
})

其他回答

虽然提供的JavaScript解决方案可以工作,但我采用了稍微不同的方式,不需要额外的JavaScript,但需要视图中的逻辑。你可以用一个标准的URL参数创建一个链接,比如:

<a href = "http://link.to.yourpage?activeTab=home">My Link</a>

然后,只需检测activeTab的值,在相应的<li>中写入'class="active"'

伪代码(在您的语言中相应地实现)。注意,如果本例中没有提供参数,我已经将'home'选项卡设置为默认活动。

$activetabhome = (params.activeTab is null or params.activeTab == 'home') ? 'class="active"' : '';
$activetabprofile = (params.activeTab == 'profile') ? 'class="active"' : '';

<li $activetabhome><a href="#home">Home</a></li>
<li $activetabprofile><a href="#profile">Profile</a></li>
$(function(){
  var hash = window.location.hash;
  hash && $('ul.nav a[href="' + hash + '"]').tab('show');
});

这段来自http://github.com/twitter/bootstrap/issues/2415#issuecomment-4450768的代码非常适合我。

基于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>

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

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

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

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

$(document).ready(function(){

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

});