Jquery ul Submenu slidetoggle issue
I'm building a shop using oscommerce and have a menu using an addon which displays an unordered list for the categories. The UL list displays like so...
<ul id='suckertree1'><li><a href='index.php?cPath=21'>Summer</a>
<ul>
<li>
<a href='index.php?cPath=21_23'>Bikes</a>
<ul>
<li><a href='index.php?cPath=21_23_28'>E-Bikes</a></li>
<li><a href='index.php?cPath=21_23_27'>Mountainroad</a></li>
<li><a href='index.php?cPath=21_23_26'>Road Bikes (1)</a></li>
</ul>
</li>
<li><a href='index.php?cPath=21_24'>Clothing</a>
<ul>
<li><a href='index.php?cPath=21_23_28'>Gloves</a></li>
<li><a href='index.php?cPath=21_23_27'>Shoes</a></li>
<li><a href='index.php?cPath=21开发者_如何学运维_23_26'>Protection</a></li>
</ul>
</li>
</ul>
</li>
<li>
<a href='index.php?cPath=22'>Winter</a>
</li>
</ul>
I'm using jquery to hide a portion of the menu. When you click on Bikes - it then displays the submenu of that. The problem I have is, that the submenu links do not link, they close the menu again..
Here is my (terrible) jQuery code
$(document).ready(function() {
$("ul#suckertree1 li ul li ul").hide();
$("ul#suckertree1 li ul li a").click(function(e) {
e.preventDefault();
$("ul#suckertree1 li ul li ul").slideToggle();
});
});
Because of the limitations with this menu, I am unable to assign classes or ID's to the menu other than the #suckertree1 already in place. How can I prevent the preventDefault() from effecting the submenu points? and also, clicking an item to only toggle the submenu below?
Thanks
James
Instead of this:
$("ul#suckertree1 li ul li ul").slideToggle();
Find the <ul>
relatively, since it's beside the <a>
you clicked that's pretty easy to get at using .siblings()
or .next()
, like this:
$(this).siblings('ul').slideToggle();
So it'd look like this:
$(function() {
$("ul#suckertree1 li ul li ul").hide();
$("ul#suckertree1 li ul li:has(ul) > a").click(function(e) {
$(this).siblings('ul').slideToggle();
e.preventDefault();
});
});
You can give it a try here
This also fixes the sub menu links working by using :has()
and the child selector (>
). What we're doing is only binding this handler to links that are in an <li>
that also contain a <ul>
element. It if doesn't have one (no sub menu) this code doesn't even run for that anchor, and it just continues to follow it's href
like normal.
精彩评论