jQuery: Selecting only ul, not ul ul

2019-08-05 08:20发布

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 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!

4条回答
甜甜的少女心
2楼-- · 2019-08-05 08:58

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();
    });
}); 
查看更多
你好瞎i
3楼-- · 2019-08-05 09:02

This is much simpler and works for me.

$(".parent").click(function() {
   $(this).children('ul').slideToggle();
});
查看更多
做个烂人
4楼-- · 2019-08-05 09:02

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()
  })

})
查看更多
Explosion°爆炸
5楼-- · 2019-08-05 09:11

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.

查看更多
登录 后发表回答