问题
this is my first post here so I apologise in advance for any poor practise. I've been searching for a while, but haven't come across a solution that fits my needs as yet - maybe I'm just doing it wrong. But here goes:
I'm building a site using the Big Cartel CMS and have delved into jQuery for the first time. I'm trying to create a horizontal and centred navigation menu that will display a sub-menu underneath, where appropriate. I'm fine with html and CSS, but am struggling with the jQuery.
The mark-up is as follows:
<nav>
<ul id="mainNav">
<li><a href="expand-the-sub-menu">Option 1</a>
<ul id="option1Nav">
<li><a href="somewhere">Option 1 Link 1</a></li>
<li><a href="somewhere">Option 1 Link 2</a></li>
<li><a href="somewhere">Option 1 Link 3</a></li>
<li><a href="somewhere">Option 1 Link 4</a></li>
<li><a href="somewhere">Option 1 Link 5</a></li>
</ul>
</li>
<li><a href="expand-the-sub-menu">Option 2</a>
<ul id="option2Nav">
<li><a href="somewhere">Option 2 Link 1</a></li>
<li><a href="somewhere">Option 2 Link 2</a></li>
<li><a href="somewhere">Option 2 Link 3</a></li>
<li><a href="somewhere">Option 2 Link 4</a></li>
<li><a href="somewhere">Option 2 Link 5</a></li>
</ul>
</li>
<li><a href="somewhere">Option 3</a></li>
<li><a href="somewhere">Option 4</a></li>
<li><a href="somewhere">Option 5</a></li>
<li><a href="somewhere">Option 6</a></li>
</ul>
</nav>
Whilst this format will not change, the number of options with sub-menus might (the client can change this at will). My jQuery so far:
$('#mainNav ul').hide();
$('#mainNav li a').click(function(){
$('#mainNav li:has("ul")').each(
function(){
$('nav').animate({bottom:'60px'},300,'easeOutQuint',function(){
//Do magic stuff here - i.e. display the correct sub-menu.
});
}
);
});
Currently, this targets all options (I can't fathom why) when clicked, and I've still not got to the bottom of how to only display the appropriate sub-menu. Classes may be added to any html elements, if that helps to make things easier.
Thanks in advance!
回答1:
How's this:
http://jsfiddle.net/qDX2q/3/
$('#mainNav ul').hide();
$('#mainNav a')
.click(function()
{
$('#mainNav ul').hide();
$(this).siblings("ul").show();
return false;
});
The things I think you were missing were:
- Making sure you return false from the click event, so that bad url is not followed.
- The
this
keyword. In the above codethis
is actually the anchor tag you are on. So you can just look for siblingul
s and show them
来源:https://stackoverflow.com/questions/11970702/making-jquery-display-the-correct-sub-menu-when-present