重新加载页面后,保持实现选项卡处于打开状态

时间:2019-06-20 13:13:09

标签: jquery html css tabs materialize

我要在重新加载页面后保持实现选项卡打开,并将链接发送给选项卡的用户,例如http://www.example.com/samplepage#tab

    <ul class="nav nav-tabs" role="tablist" id="userdashboard-tabs">
     <li class="nav-item">
      <a class="nav-link active" data-toggle="tab" href="#Dashboard" role="tab" aria-controls="Dashboard">Dashboard</a>
</li>
<li class="nav-item">
<a class="nav-link" data-toggle="tab" href="#Orders" role="tab" aria-controls="Orders">My Orders</a> </li>
<li class="nav-item">
<a class="nav-link" data-toggle="tab" href="#Products" role="tab" aria-controls="Products">My Products</a>
</li>
<li class="nav-item">
 <a class="nav-link" data-toggle="tab" href="#Sells" role="tab" aria-controls="Sells">My Sells</a>
 </li>
   <li class="nav-item">
  <a class="nav-link" data-toggle="tab" href="#Account" role="tab" aria-controls="Account">My Account</a></li>
                        </ul>

这是javascript:

$(document).ready(function () {
    $('#userdashboard-tabs a').click(function(e) {
    e.preventDefault();
    $(this).tabs();
  });

  // store the currently selected tab in the hash value
  $("ul.nav-tabs > li > a").on("click", function(e) {
    var id = $(e.target).attr("href").substr(1);
    console.log(id + "dijdljsodfj");
    window.location.hash = id;
  });

  // on load of the page: switch to the currently selected tab
  var hash = window.location.hash;
  console.log(hash +"hash");
  $('#userdashboard-tabs a[href="' + hash + '"]').click();

})

页面重新加载会出现此错误:

jquery-3.0.0.min.js:2 jQuery.Deferred exception: Cannot read property 'classList' of undefined TypeError: Cannot read property 'classList' of undefined

单击标签会出现此错误:

materialize.js:4019 Uncaught TypeError: Cannot read property 'parentNode' of undefined

1 个答案:

答案 0 :(得分:1)

我知道有点晚了,但这对我有用:

在每个标签锚中,我都设置了数据切换属性:

<a data-toggle="tab"

然后我像这样使用选项卡配置:

// Init tabs
$(".tabs").tabs();

// Show active tab on reload
if (location.hash !== '') {
  $('.tabs').tabs('select', location.hash);
}

// Remember the hash in the URL without jumping
$('a[data-toggle="tab"]').click(function(e) {
  if (history.replaceState) {
    history.replaceState(null, null, '#' + $(e.target).attr('href').substr(1));
  } else {
    location.hash = '#' + $(e.target).attr('href').substr(1);
  }

  $(window).trigger('hashchange');
});
相关问题