简体   繁体   English

在页面重新加载后保持活动标签时加载 ajax 内容(引导程序 4)

[英]Load ajax content when keep active tab after page reload (Bootstrap 4)

I created a page with many tabs In order not to slow down the loading of the page during the first display, I get the content of the tabs only if we click on it我创建了一个包含许多选项卡的页面 为了在第一次显示时不减慢页面的加载速度,我只有在单击时才能获取选项卡的内容

I then set this up to save the last active tab :然后我将其设置为保存最后一个活动选项卡:

$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
    localStorage.setItem('activeTab', $(e.target).attr('href'));
});

var activeTab = localStorage.getItem('activeTab');
if(activeTab){
    $('.nav-tabs a[href="' + activeTab + '"]').tab('show');
}

It works well, when I reload the page I fall well on the last tab visited效果很好,当我重新加载页面时,我会很好地落在最后访问的选项卡上

But problem, it does not load Ajax content (or even a simple alert)但问题是,它不会加载 Ajax 内容(甚至是简单的警报)

DEMO : https://jsfiddle.net/ak37besp/1/演示: https : //jsfiddle.net/ak37besp/1/

How to get to the last tab used and then load the corresponding Ajax ?如何到达使用的最后一个选项卡,然后加载相应的 Ajax ?

The problem in your code is that you're not calling any function that loads the ajax content after you reload the page, you're only setting the active tab.您的代码中的问题在于,您没有在重新加载页面后调用任何加载 ajax 内容的函数,您只是在设置活动选项卡。

to do that, create a function in your code called loadTabContent(tab) that takes the tab id as a parameter and load the ajax content:为此,请在您的代码中创建一个名为loadTabContent(tab)的函数,该函数将选项卡 ID 作为参数并加载 ajax 内容:

function loadTabContent(tab) {
    if (tab == '#tab2'){
    alert("ajax loaded tab2");
    //load ajax content for tab 2 here
  }
}

And then when checking and setting an active tab from localStorage, call the created function:然后在从 localStorage 检查和设置活动选项卡时,调用创建的函数:

// read hash from page load and change tab
var activeTab = localStorage.getItem('activeTab');
if(activeTab){
  $('.nav-tabs a[href="' + activeTab + '"]').tab('show');
  loadTabContent(activeTab);
}

And here's a demo link: https://jsfiddle.net/1mfqwgpz/3/这是一个演示链接: https : //jsfiddle.net/1mfqwgpz/3/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM