0

我有一个包含国家列表和城市子列表的页面。为了简单起见,我制作了一个只有几个菜单和一个子菜单的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

JSfiddle 似乎没有加载 jQuery cookie 插件,但我正在尝试的是,在单击数组后设置主菜单的名称。当页面加载时,它会检查 cookie,如果有,数组中将是加载时应该扩展的主菜单项。

4

1 回答 1

2

我已经修改了你的代码。请参阅内联注释。在此处查看完整代码和LIVE 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();
    }
});
于 2013-07-15T18:24:17.527 回答