2011-11-05 65 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

相關問題