本文介绍了使用Cookie保持jQuery菜单保持打开状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在玩我在本网站上发现的一些jQuery cookie,以及我认为正在运行的cookie,但我的菜单完全停止打开.

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.

我对jQuery很陌生,所以不确定在哪里出错.

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

我只是一直打开链接,例如,单击链接1,然后单击一个子菜单项,当页面加载时,链接1仍处于打开状态.

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!

谢谢

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

});

推荐答案

这是一个比较混乱的答案:

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

您需要为此添加 jquery.cookie 库.

可以在这里找到更新的小提琴: http://jsfiddle.net/pHgB7/2/

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

这篇关于使用Cookie保持jQuery菜单保持打开状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 13:14