#id 在页面 URL 中时不显示选项卡

Tabs not shown when #id is in page URL

我尝试向我的页面添加选项卡选项 URL 以便在页面加载时聚焦指定的选项卡

示例:mywebsite/page/#tab3

我正在使用 jQuery,但不是 jQuery UI。

有什么办法可以做到吗?

<div class="wrapper">

<ul class="tabs clearfix" data-tabgroup="first-tab-group">
  <li><a href="#tab1" class="active">Tab 1</a></li>
  <li><a href="#tab2">Tab 2</a></li>
  <li><a href="#tab3">Tab 3</a></li>
</ul>

<section id="first-tab-group" class="tabgroup">
  <div id="tab1">
    <h2>Heading 1</h2>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nulla deserunt consectetur ratione id tempore laborum laudantium facilis reprehenderit beatae dolores ipsum nesciunt alias iusto dicta eius itaque blanditiis modi velit.</p>
  </div>
  <div id="tab2">
    <h2>Heading 2</h2>
    <p>Adipisci autem obcaecati velit natus quos beatae explicabo at tempora minima voluptates deserunt eum consectetur reiciendis placeat dolorem repellat in nam asperiores impedit voluptas iure repellendus unde eveniet accusamus ex.</p>
  </div>
  <div id="tab3">
    <h2>Heading 3</h2>
    <p>Atque ratione soluta laboriosam illo inventore amet ipsum aliquam assumenda harum provident nam accusantium neque debitis obcaecati maxime officia saepe ad ducimus in quam libero vero quasi. Saepe sit nisi?</p>
  </div>
</section>

</div>
$('.tabgroup > div').hide();
$('.tabgroup > div:first-of-type').show();
$('.tabs a').click(function(e){
  e.preventDefault();
    var $this = $(this),
        tabgroup = '#'+$this.parents('.tabs').data('tabgroup'),
        others = $this.closest('li').siblings().children('a'),
        target = $this.attr('href');
    others.removeClass('active');
    $this.addClass('active');
    $(tabgroup).children('div').hide();
    $(target).show();
})    
$(document).ready(function(){
  if (document.location.hash != '') {
    $(".active").removeClass("active");
    $('a[href*="' + document.location.hash + '"]').addClass("active");
    $('[id^=tab]').hide();
    $(document.location.hash).show();
  }
});

一种简单的方法是使用 filter() 到 return 与 url 哈希匹配的选项卡并触发对其的点击。

$('.tabs a').filter(function(){ return this.hash === location.hash; }).click();