开发者

jQuery: Selecting only ul, not ul ul

I'm trying to beat a basic accordion style menu into submission – using jQuery.

Here's the menu:

http://www.cybart.com/bscg/

Here's 开发者_StackOverflow中文版a snippet of code that gives it accordion functionality:

$('#access ul li').click(function(){
        $('#access ul ul:visible').slideUp();
        $(this).children('ul:hidden').slideDown();

    });

The problem: a click on a sub-menu link makes the submenu slide up (and close).

I want to keep the submenu open when the submenu link is clicked, and slide up only when a top level links are clicked.

How can I select only the top level ul with jQuery to animate the submenu? Or is there a way to select the sub-menu link and "tell it" to keep the submenu open on click?

I would appreciate your wisdom!


It seems like you need to use the > operator in CSS.

.foo > .bar selects all elements with class bar that is a direct child of an element with class foo

Got it, working code:

$('#access ul.menu > li > a').click(function(){
        $('#access ul ul:visible').slideUp();
        $(this).siblings('ul').slideDown();
    });
}); 

To keep the menu from sliding back up again this works:

$('#access ul.menu > li > a').click(function(){
        var siblingUl = $(this).siblings('ul');
        if(siblingUl.is(':visible')) { // The currently open menu was clicked
            // Remove this if you want nothing to happen
            siblingUl.slideUp();
            return;
        }

        $('#access ul ul:visible').slideUp();
        siblingUl.slideDown();
    });
}); 


You can't stop the menu from closing because the browser is making a new request and loading the menu fresh when you click on the links. Just watch the URL bar. When you click the sub-menu links, the URL changes.

You'll need to add something to the URL to stop the sub-menu from collapsing, or test the URL to see if it should re-open the accordion after the page loads.


This is much simpler and works for me.

$(".parent").click(function() {
   $(this).children('ul').slideToggle();
});


i have took 10 minutes to read and understand your code because you have a lot of styles and id's and this is complicating it a lot, take care of the best practices

All you need is something like

<ul>
  <li>
   <a class="menu">Menu</a>
    <ul>
       <li><a>Submenu</a></li>
    </ul>
  </li>
  <li>Other menu</li>
</ul>

...

$(document).ready(function(){

  $(".menu").click(function(){
      $(this).next().toggle()
  })

})
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜