2011-11-05 67 views
2

假设我们在页面上有一个侧栏。它有两个选项卡。当您单击未选定的选项卡时,边栏下面的内容会立即使用jQuery进行切换。旧的div被隐藏,显示新的div。没什么大不了的。JS:在页面重新加载时保持用户选择持续

现在你已经选择了不过div的,当你点击到下一个页面,该选择的历史记录丢失,而你又回到了第一个默认选择的股利。

我怎样才能保持持久的行动?

+0

所以,如果我得到了正确的选项卡应刷新页面后选择? –

+0

正确的 - 同样的侧边栏出现在每一页上 - 所以,如果它的刷新或点击不同的网页 - 它应该是持久的 – Elliot

回答

0

使用cookie来跟踪哪些选择选项卡。

$.cookie('tabSelected', 'news'); 

在pageload上自动选择来自cookie值的选项卡或默认值(如果没有设置cookie)。你可以找到的jQuery插件饼干here

这是假设的标签的事情只是一个小的用户偏好,而不是整个网站的导航机制。

0

你可能想看看jQuery Cookie。沿着这些线路

假设HTML:

<ul class="tabs"> 
    <li class="tab" id="tab1"> 
     ... 
    </li> 
    <li class="tab" id="tab2"> 
     ... 
    </li> 
</ul> 

这会工作:

$(document).ready(function(){ 
    $('.tab').click(function(){ 
     // show correct tab, hide other tabs ... 
     $.cookie('selected_tab', $(this).attr('id')); // save information in a cookie 
    }); 

    current_tab = $.cookie('selected_tab'); // read and cache information from cookie 

    if (current_tab != null) 
    { 
     $('#' + current_tab).trigger('click'); // trigger the tab click handler, thereby restoring the tab 
    } 
}); 

另一种选择将是一个锚连接到一个表示当前选择的选项卡每个链接的URL并对其进行评估页面加载:

$(document).ready(function(){ 
    $('.tab').click(function(){ 
     // show correct tab, hide other tabs ... 

     var current_id = $(this).attr('id'); // cache the current tab id 

     $('a').each(function(i,e){ // add a hash '#tab=tab1' to each link in the page 
      hrf = $(e).attr('href'); 
      if (hrf) { 
       $(e).attr('href', hrf.split('#')[0] + '#tab=' + current_id); 
      }); 
     }); 
    }); 

    current_tab = document.location.hash.split('tab=')[1]; 

    if (current_tab) // if '#tab=foo' is present in the URL 
    { 
     $('#' + current_tab).trigger('click'); // trigger the tab click handler, thereby restoring the tab 
    } 
}); 

这种方式显然有它自己的问题,尽管(即无法使用哈希链接作为那些被覆盖)。

+0

............还是? – Triptych

+0

@Triplech还是什么? – vzwick

+0

看看你自己的修订历史哈哈。 – Triptych

相关问题