Maintaining jQuery-ui previous active tab (before reload) on page reload

前端 未结 2 1831
無奈伤痛
無奈伤痛 2021-01-16 09:31

I have a jquery-ui tab component with two tabs.


                      
相关标签:
2条回答
  • 2021-01-16 10:19

    Use browser sessionStorage to store the tab index,

    something like this:

    $(document).ready(function () {
        var currentTabIndex = "0";
    
        $tab = $("#tabs").tabs({
             activate : function (e, ui) {
                currentTabIndex = ui.newTab.index().toString();
                sessionStorage.setItem('tab-index', currentTabIndex);
             }
        });
    
        if (sessionStorage.getItem('tab-index') != null) {
            currentTabIndex = sessionStorage.getItem('tab-index');
            console.log(currentTabIndex);
            $tab.tabs('option', 'active', currentTabIndex);
        }
        $('#btn-sub').on('click', function () {
            sessionStorage.setItem("tab-index", currentTabIndex);
            //window.location = "/Home/Index/";
        });
    });
    

    this will update the sessionStorage on changing the tab, try updating the tab by using your condition. I hope it helps.

    here is the Demo for local storage

    You can remove the sessionStorage by using sessionStorage.removeItem('tab-index');

    sessionStorage is cleared automatically when the browser is closed. It works in pretty much the same way as localStorage.

    here is the Demo for sessionStorage

    0 讨论(0)
  • 2021-01-16 10:20

    I found the way to store the id of the currently active tab in to the hidden variable. Take a look at this demo JSFIDDLE. As you get the id of the currently active tab form the hidden input element store it in the session or DB and when the page reloads fetch that value and set that in active: option of tabs.

    HTML:

    Currently active tab: <input type="text" id="active_tab">
    <div id="tabs">
    <ul>
    <li><a href="#tabs-1" id="1">Tab 1</a></li>
    <li><a href="#tabs-2" id="2">Tab 2</a></li>
    <li><a href="#tabs-3" id="3">Tab 3</a></li>
    </ul>
    <div id="tabs-1">
    <p>Tab 1 content</p>
    </div>
    <div id="tabs-2">
    <p>Tab 2 content</p>
    </div>
    <div id="tabs-3">
    <p>Tab 3 content</p>
    </div>
    </div>
    

    JS :

    $(function() {
         $( "#tabs" ).tabs({
             active: 2,
             activate: function( event, ui ) {
                 var active = $( ".selector" ).tabs( "option", "active" );
                 console.log(active);
                 $('#active_tab').val(active.context.activeElement.id);
             }
         });
    
    });
    
    0 讨论(0)
提交回复
热议问题