Make jquery tabs remember selection

夙愿已清 提交于 2021-01-28 12:29:02

问题


I have this jquery code:

<script type="text/javascript">
  $(document).ready(function() {
    $(".tabLink").each(function(){
      $(this).click(function(){
        tabeId = $(this).attr('id');
        $(".tabLink").removeClass("activeLink");
        $(this).addClass("activeLink");
        $(".tabcontent").addClass("hide");
        $("#"+tabeId+"-1").removeClass("hide")   
        return false;     
      });
    });  
  });
</script>

and this HTML:

<div class="tab-box"> 
<a href="javascript:;" class="tabLink activeLink" id="companyinfo">Company</a> 
<a href="javascript:;" class="tabLink" id="contacts">Contacts</a>
</div>

<div class="tabcontent" id="companyinfo-1">
content 1 here
</div>

<div class="tabcontent" id="contacts-1">
content 2 here
</div>

if the page is refreshed, the first tab is selected again. how can i make it remember my selection if the page is refreshed?


回答1:


You can save the index of the clicked tab in localStorage.

 // on click, save it in localStorage.selectedTab
localStorage.selectedTab = $(this).index() + 1;

// on document ready, after click handler was added search for it
if (localStorage.selectedTab) {
  $(".tabLink:eq(" + (localStorage.selectedTab - 1) + ")").click();
}

JSFIDDLE

Another solution would be using cookies, but I find localStorage easier.


Also, you can use the active field in the tabs API using, like Atakan Aral said:

$("#tabs").tabs({
    activate: function( event, ui ) {
        localStorage.selectedTab = ui.newTab.index() + 1;
    },
    active: localStorage.selectedTab ? localStorage.selectedTab - 1 : 0
});



回答2:


A more compact jQuery UI version of ionică-bizău's answer:

$("#tabs").tabs({
    activate: function( event, ui ) {
        localStorage.selectedTab = ui.newTab.index() + 1;
    },
    active: localStorage.selectedTab ? localStorage.selectedTab - 1 : 0
});


来源:https://stackoverflow.com/questions/18760763/make-jquery-tabs-remember-selection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!