Keeping A jQuery menu open with cookies

帅比萌擦擦* 提交于 2020-01-06 15:13:34

问题


I've been playing around with some of the jQuery cookies I've found across this site and the cookie I think is working but my menu stops opening altogether.

I'm very new to jQuery so not sure where I could be going wrong.

I just went to keep open the links e.g click link 1 and then a sub-menu item and when the page loads, link 1 is still open.

Someone please point me in the right direction!

Thank you

http://jsfiddle.net/pHgB7/

<ul class="nav">
<li><a>Link</a>

</li>
<li class="drop"><a>Link 1</a>

    <ul id="m1">
        <li><a href="#">Link 1 Item</a>

        </li>
        <li><a href="#">Link 1 Item</a>

        </li>
    </ul>
</li>
<li class="drop"><a>Link 2</a>

    <ul id="m2">
        <li><a href="#">Link 2 Item</a>

        </li>
        <li><a href="#">Link 2 Item</a>

        </li>
    </ul>
</li>
<li class="drop"><a>Link 3</a>

    <ul id="m3">
        <li><a href="#">Link 3 Item</a>

        </li>
        <li><a href="#">Link 3 Item</a>

        </li>
    </ul>
</li>

jQuery(function ($) {
// jQuery code in here can safely use $
$('.nav li')
.css({
cursor: "pointer"
})
$(".drop")
    .on('click', function () {
    $(this).find('ul').toggle();
})

});

回答1:


Here's a little messier answer:

jQuery(function ($) {
    // jQuery code in here can safely use $
    $('.nav li')
        .css({
            cursor: "pointer"
        });

    $(".drop")
        .on('click', function () {
            $(this).toggleClass('open');
            $(this).find('ul').toggle();
            $.cookie('open_items', 'the_value');
            openItems = new Array();
            $("li.drop").each(function(index, item) {
                if ($(item).hasClass('open')) {
                    openItems.push(index);
                }
            });
            $.cookie('open_items', openItems.join(','));
        });

    if( $.cookie('open_items') && $.cookie('open_items').length > 0 ) {
        previouslyOpenItems = $.cookie('open_items');
        openItemIndexes = previouslyOpenItems.split(',');
        $(openItemIndexes).each(function(index, item) {
            $("li.drop").eq(item).addClass('open').find('ul').toggle();
        });
    }
});

You'll need to include the jquery.cookie library for this.

Updated fiddle can be found here: http://jsfiddle.net/pHgB7/2/



来源:https://stackoverflow.com/questions/20396116/keeping-a-jquery-menu-open-with-cookies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!