最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery show submenu if parent have been clicked - Stack Overflow

programmeradmin6浏览0评论

Could some one please help with code.

I want to show the submenu only when submenu parent is clicked.

HTML

<ul>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a>
    <ul class="sub-menu">
        <li><a href="#">Submenu</a></li>
        <li><a href="#">Submenu</a></li>
    </ul>
</li>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a>
    <ul class="sub-menu">
        <li><a href="#">Submenu</a></li>
        <li><a href="#">Submenu</a></li>
    </ul>
</li>
<li><a href="#">Item</a></li>
</ul>

So if you click on the parent submenu will show.

Here is fiddle link - /

Could some one please help with code.

I want to show the submenu only when submenu parent is clicked.

HTML

<ul>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a>
    <ul class="sub-menu">
        <li><a href="#">Submenu</a></li>
        <li><a href="#">Submenu</a></li>
    </ul>
</li>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a>
    <ul class="sub-menu">
        <li><a href="#">Submenu</a></li>
        <li><a href="#">Submenu</a></li>
    </ul>
</li>
<li><a href="#">Item</a></li>
</ul>

So if you click on the parent submenu will show.

Here is fiddle link - http://jsfiddle.net/KhNCV/1/

Share Improve this question asked Nov 22, 2011 at 18:52 Kaspars MilbergsKaspars Milbergs 7847 gold badges14 silver badges26 bronze badges 0
Add a comment  | 

5 Answers 5

Reset to default 10
$('.sub-menu').hide();

$("li:has(ul)").click(function(){

$("ul",this).slideDown();
});

http://jsfiddle.net/3nigma/KhNCV/2/

OR

$('.sub-menu').hide();

$("li:has(ul)").click(function(){

$("ul",this).toggle('slow');
});

http://jsfiddle.net/3nigma/KhNCV/4/

Here's your example working. It's unclear why you need the a tags, as you could use cursor: pointer in the CSS to make the li appear clickable. I'll assume you want to do some spiffy hovering on them in IE that's CSS only? If not, you could simplify by removing them.

Instead of doing hide() on .submenu, you should use CSS (parsed with DOM instead of onReady/load).

.sub-menu { display: none; }

And then here's you code to toggle the menus:

$('ul li a').click(function() {
    $(this).parent().find('ul.sub-menu').toggle();
    return false;
});
$('.sub-menu').hide();

$("a").click(function(){

    $(this).parent().children("ul").toggle();

})

check out this link http://jsfiddle.net/KhNCV/6/

$('li a').click(
function() {
    $(this).next().slideToggle();
})

Try this

$(function(){

   //Hide all the sub menus
   $('.sub-menu').hide();

   $("li:has(ul)").click(function(){
      //Find the child ul and slideToggle
      $(this).children("ul").slideToggle();
   });
});
发布评论

评论列表(0)

  1. 暂无评论