JS:在页面重新加载时保持用户选择的持久性

时间:2011-11-05 12:57:55

标签: javascript jquery

让我们说我们在页面上有一个侧栏。它有两个选项卡。单击未选中的选项卡时,侧栏中其下方的内容会立即使用jQuery切换。隐藏旧的div,显示新的div。没有大碍。

现在您已经选择了该div,但是当您单击下一页时,该选择的历史记录将丢失,并且您将返回到第一个默认选定的div。

如何保持行动持久?

2 个答案:

答案 0 :(得分:0)

使用Cookie跟踪选择的标签。

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

在页面加载时,如果未设置cookie,则自动从cookie值中选择选项卡或默认值。你可以找到jQuery cookie插件here

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

答案 1 :(得分: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,该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
    }
});

这种方法显然有其自身的问题(即无法使用散列链接,因为这些会被覆盖)。