单击菜单时设置cookie,以便下一个访问菜单打开

时间:2013-07-15 17:56:14

标签: javascript jquery cookies jquery-cookie

我有一个包含国家/地区列表的页面及其城市的子列表。为了简单起见,我只用几个菜单和一个子菜单<{3}}制作了http://jsfiddle.net/PPexP/7/

javascript的简短预览 和jquery.cookie链接:https://raw.github.com/carhartl/jquery-cookie/master/jquery.cookie.js

$(document).ready(function(){
function checkCookie() {
    if($.cookie('mainlevel')) {
        var array = [];
        array.push($.cookie('mainlevel'));
        console.log(dirArray)
    }
} 

$('.mainitem').click(function() {    
    var $cookie = ($(this).text());
    console.log($cookie)
    $cookie = $cookie.split(',');
    $(this).next('ul').toggle(function() {
        console.log('fired');
        var CookieSet = $.cookie('mainlevel', [$cookie], { expires: 30 });
    });
});

});

生成HTML并且就像在JSFIDDLE中一样,我无法更改html。

应该发生什么:

  1. 当点击主菜单项时,弹出子菜单并设置cookie,以便下次菜单仍然打开。它会检查主菜单的名称,这将是cookie
  2. JSfiddle似乎没有加载jQuery cookie插件,但我想要的是,在数组中单击后设置主菜单的名称。当页面加载时,它会检查cookie,如果有的话,在数组中将是应该在加载时扩展的主菜单项。

1 个答案:

答案 0 :(得分:2)

我修改了你的代码。请参阅内联评论。请参阅整个代码hereLIVE DEMO

$('.subitems').hide();

// check cookie
checkCookie();

function checkCookie() {
    // the cookie exists
    if($.cookie('mainlevel')) {
        var index = $.cookie('mainlevel');
        $(".mainitem:eq(" + index + ")").find("ul").show();
    }
}

// click on .mainitem
$('.mainitem').click(function() {
    // get the index
    var cookie = $(this).index();

    // hide all subitems
    $(".mainitem").find("ul").slideUp();

    // toggle the ul that is in the clicked item
    $(this).find('ul').toggle(function() {
        // save the cookie
        $.cookie('mainlevel', [cookie], { expires: 30 });
    });

    // toggle if change happend :: thanks @lolotron
    if (previousValue != cookie) {            
        $(".mainitem").find("ul").slideUp();        
        $(this).find('ul').slideDown();
    }
});