Can I keep on same jQuery tab on page refresh or when I have navigated away from the page?

前端 未结 3 1321
情话喂你
情话喂你 2020-12-07 00:00

I have a basic jQuery tabs system going:

$(document).ready(function(){
  $(\'#tabs div.jdiv\').hide();
  $(\'#tabs div.jdiv:first\').fadeIn(\"slow\");
  $(\'         


        
相关标签:
3条回答
  • 2020-12-07 00:20

    Not easily. The client side script is reloaded when you refresh the page, and all changes will be undone, unless of course you store it somewhere — possibly as a URL parameter?

    0 讨论(0)
  • 2020-12-07 00:25

    To preserve the current tab open after the page is refreshed only solution coming in my mind is using cookies, I think it's the only one.

    If you use a link in the web page, on the other hand, to refresh the page you could add an anchor to it with the tab opened at the time.

    0 讨论(0)
  • 2020-12-07 00:37

    You can use hash tags to uniquely identify each tab, so http://example.com/yourpage.html#current-points takes you to the current-points tab, and http://example.com/yourpage.html#my-details takes you to the my-details tab. You can set the hash by assigning to location.hash, and of course you can read that on page load. This also has the huge advantage that your users can bookmark the tabs they want. You can use a path in the hash if you have tabs within tabs (so #first/foo takes you to the first tab and its foo subtab; #first/bar takes you to the first tab and its bar subtab).

    Here's a really basic example (without subtabs, but you get the idea):

    Live copy | Live source

    HTML:

    <ul id="nav">
        <li><a href="#first">First</a></li>
        <li><a href="#second">Second</a></li>
        <li><a href="#third">Third</a></li>
    </ul>
    <div class="tab" id="tab-first">This is first</div>
    <div class="tab" id="tab-second">This is second</div>
    <div class="tab" id="tab-third">This is third</div>
    

    JavaScript:

    jQuery(function($) {
    
        $("<p>").html("Loaded at " + new Date()).appendTo(
            document.body
        );
        showTab(location.hash || "first");
    
        $("#nav a").click(function() {
            var hash = this.getAttribute("href");
            if (hash.substring(0, 1) === "#") {
                hash = hash.substring(1);
            }
            location.hash = hash;
            showTab(hash);
            return false;
        });
    
        function showTab(hash) {
            $("div.tab").hide();
            $("#tab-" + hash).show();
        }
    
    });
    

    Alternately (or in conjunction), you can set a cookie when they change tabs, and check for the cookie on page load to select the last tab they had selected.

    0 讨论(0)
提交回复
热议问题