Remember which tab was active after refresh

前端 未结 17 2232
眼角桃花
眼角桃花 2020-11-27 04:43

I\'m using jquery tabs on a web page and when the page is refreshed it loses what ever tab I had been on and goes back to the first tab.

Has anyone come across this

17条回答
  •  鱼传尺愫
    2020-11-27 05:03

    If you're using bootstrap 3 or 4 tabs, you could use local storage to store the current tab id then set it to show on page load. First you'll prevent the default method to open the tab, then save the opened tab link id on tab open event.

     $('a[data-toggle="tab"]').click(function (e) {
            e.preventDefault();
            $(this).tab('show');
        });
    
        $('a[data-toggle="tab"]').on("shown.bs.tab", function (e) {
            var id = $(e.target).attr("href");
            localStorage.setItem('selectedTab', id)
        });
    
        var selectedTab = localStorage.getItem('selectedTab');
    
        if (selectedTab != null) {
            $('a[data-toggle="tab"][href="' + selectedTab + '"]').tab('show');
        }
    

    Always works fine for me.

提交回复
热议问题