使用Turbolink以编程方式打开Bootstrap选项卡

时间:2020-05-16 20:04:04

标签: javascript bootstrap-4 turbolinks bootstrap-native

我正在尝试在页面加载后打开Bootstrap 4选项卡。如果刷新页面,它确实可以工作,但是如果我在站点中导航,则会收到查询选择器为空的错误。

这是我的代码,基本上是我为此https://webdesign.tutsplus.com/tutorials/how-to-add-deep-linking-to-the-bootstrap-4-tabs-component--cms-31180做的一个端口,因为我使用的是Bootstrap-native,所以我不得不用原始Javascript重写它。

  document.addEventListener("turbolinks:load", function() {
    let url = location.href.replace(/\/$/, "");
    if (location.hash) {
      const hash = url.split("#");
      document.querySelector('#nav-tab a[href="#'+hash[1]+'"]').Tab.show();
      url = location.href.replace(/\/#/, "#");
      history.replaceState(null, null, url);
      setTimeout(() => {
        window.scrollTo(0,0);
      }, 400);
    }
  });

我将其放置在结束标签前。如果我写http://www.myURL#mytab并单击刷新,则页面刷新和选项卡会更改,但是如果我从(涡轮)链接到达那里,它将找不到要查询选择的选项卡。恐怕问题出在“加载”事件上,我尝试了其他方法,但无法正常工作。

1 个答案:

答案 0 :(得分:2)

如果您要在<script>末尾的<body>中包含此代码,则可能不需要侦听turbolinks:load事件。 为什么??第一次加载时,浏览器将能够查询位于脚本元素之前的所有元素。在Turbolinks上,<body>中的加载脚本将有权访问页面上所有呈现的元素。

值得补充的是,通过在正文document.addEventListener("turbolinks:load", …)元素中调用<script>,将在每个随后的页面加载中调用侦听器,而不仅是在脚本所在的页面上被渲染。如果 #nav-tab元素在后续页面加载中不存在,那么您将看到querySelector错误。而且,如果将脚本包含在多个页面上,那么侦听器将一次又一次地被复制,这可能不是您想要的!

因此,解决您的问题的第一步是删除事件侦听器。我们会将您的代码包装在立即调用的函数中,以防止污染全局范围:

;(function() {
  let url = location.href.replace(/\/$/, "");
  if (location.hash) {
    const hash = url.split("#");
    document.querySelector('#nav-tab a[href="#'+hash[1]+'"]').Tab.show();
    url = location.href.replace(/\/#/, "#");
    history.replaceState(null, null, url);
    setTimeout(() => {
      window.scrollTo(0,0);
    }, 400);
  }
})();

接下来要知道的是,Turbolinks管理着自己的已访问页面缓存,因此,当用户点击“返回”时,就会从该缓存中呈现页面。为此,它具有一个用于添加到浏览器自己的history堆栈的系统。如果绕过Turbolinks系统,并且自己致电history.replaceState(或history.pushState),那么最终可能会破坏“后退”导航。 Turbolinks没有记录的方法可以手动添加到其历史记录堆栈,但是您可以尝试以下操作:

;(function() {
  let url = location.href.replace(/\/$/, "");
  if (location.hash) {
    const hash = url.split("#");
    document.querySelector('#nav-tab a[href="#'+hash[1]+'"]').Tab.show();
    url = location.href.replace(/\/#/, "#");
    Turbolinks
      .controller
      .replaceHistoryWithLocationAndRestorationIdentifier(url, Turbolinks.uuid())
    setTimeout(() => {
      window.scrollTo(0,0);
    }, 400);
  }
})();

注意,这是未记录的,因此在以后的版本中可能不会公开提供。

最后,可能值得考虑将此代码片段包含在您的主应用程序JavaScript软件包中,并将其加载到<head>中而不是正文中。在这种情况下,您需要使用`turbolinks:load处理程序。看起来可能像这样:

document.addEventListener('turbolinks:load', function () {
  let url = location.href.replace(/\/$/, "");
  const hash = url.split("#");
  const navLink = document.querySelector('#nav-tab a[href="#'+hash[1]+'"]')
  if (location.hash && navLink) {
    navLink.Tab.show();
    url = location.href.replace(/\/#/, "#");
    Turbolinks
      .controller
      .replaceHistoryWithLocationAndRestorationIdentifier(url, Turbolinks.uuid())
    setTimeout(() => {
      window.scrollTo(0,0);
    }, 400);
  }
});