簡體   English   中英

單擊菜單時設置cookie,以便下一個訪問菜單打開

[英]Set a cookie when clicked on menu so next visit menu is open

我有一個頁面,其中包含國家列表及其城市的子列表。 為了簡單起見,我做了一個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,如果有的話,在數組中將是應該在加載時擴展的主菜單項。

我修改了你的代碼。 請參閱內聯評論。 請參閱此處的完整代碼和現場演示

$('.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();
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM