1

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?

4

2 回答 2

3

ionică-bizău 答案的更紧凑的 jQuery UI 版本:

$("#tabs").tabs({
    activate: function( event, ui ) {
        localStorage.selectedTab = ui.newTab.index() + 1;
    },
    active: localStorage.selectedTab ? localStorage.selectedTab - 1 : 0
});
于 2014-10-03T20:40:26.440 回答
0

您可以将单击的选项卡的索引保存在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

另一种解决方案是使用 cookie,但我发现 localStorage 更容易。


此外,您可以使用API 中的active字段,如Atakan Aral所说:tabs

$("#tabs").tabs({
    activate: function( event, ui ) {
        localStorage.selectedTab = ui.newTab.index() + 1;
    },
    active: localStorage.selectedTab ? localStorage.selectedTab - 1 : 0
});
于 2013-09-12T09:51:05.137 回答