So, I'm creating a submenu by myself by following the jQuery c开发者_StackOverflow中文版odex only and I got stuck. Everything else is perfect, though.
I have an HTML structure like the following:
<li><a href="#">smth</a>
<ul>
<li><a href="#">smth sub</a></li>
</ul>
</li>
<li><a href="#">smth</a>
<ul>
<li><a href="#">smth sub 2</a></li>
</ul>
</li>
And let's say that the first SMTH is opened. Now, when I click on the second SMTH it will just appear on top of the other one.
My jQuery code is as follows.
$(document).ready(function() {
/*
* header navigation
*/
// hide sub UL's
$('ul.sub').hide();
$('#header .left li.m:first a, #header .right li.m:first a').css('borderLeft', 'none');
$('#header .left li.m:last a, #header .right li.m:last a').css('borderRight', 'none');
// Add class closed, because it's nessesery.
$('#header .left li ul').addClass('closed');
// If LI element is clicked, open or close sub UL?
$('#header .left li').click(function(event)
{
// If sub UL is closed, we need to open it.
if( $(this).find('ul').hasClass('closed') )
{
$(this).find('ul').removeClass('closed');
$(this).find('ul').addClass('opened');
$(this).find('ul').fadeIn('100');
}
// If sub UL is opened, we need to close it.
else
{
$(this).find('ul').removeClass('opened');
$(this).find('ul').addClass('closed');
$(this).find('ul').fadeOut('100');
}
});
});
It appears that your click function is showing and hiding the element you clicked on properly, but it is not hiding all other ul's that may be open already. Consider making the first line something like:
$(".subNav").switchClass( "open", "closed", 100 );
Which brings up a good point as well. JQuery has a switchClass() function that is nearly identical to your 3 lines of remove -> add -> fade. A great way to save some lines of code.
EDIT: I should also note that the line of js I wrote here requires that you add a class to all of your ul's that are for sub navigation. There are other ways to do this, but for the purpose of easy explanation, this seemed most fitting.
I'm not entirely sure I got the image right, because I don't know how you're styling your menu, so I'll assume it's a vertical list of SMTHs with sublists showing to the right.
What you want to do is close all opened sublists (this will normally be only one sublist) when you click on the SMTH, before you add the "opened" class.
This is how I'd modify your code:
// ...
// if LI element is clicked, open or close sub UL?
$('#header .left li').click(function(event)
{
// if sub UL is closed, we need to open it
if( $(this).find('ul').hasClass('closed') )
{
// close all opened sublists
$('ul.opened')
.removeClass('opened')
.addClass('closed')
.fadeOut('100');
// ...
Also, Ben Roux's switchClass advice is great, you should consider it.
精彩评论