问题
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